2012-06-12 40 views
2

我有一個程序和一個帶有一些信息行的.l2p文件。 我已經運行註冊表文件:Qt - 通過雙擊打開一個自定義文件

Windows Registry Editor Version 5.00 

[HKEY_CLASSES_ROOT\.l2p\DefaultIcon] 
@="\"C:\\Program Files\\ToriLori\\L2P.exe\",0" 

[HKEY_CLASSES_ROOT\.l2p\shell\Open\command] 
@="\"C:\\Program Files\\ToriLori\\L2P.exe\" \"%1\"" 

當我雙擊.l2p文件的程序啓動,但不加載該文件。我需要做些什麼才能正確加載?示例代碼將非常感激。

回答

7

當您在文件雙擊文件名作爲命令傳遞對相關程序的行參數。你必須解析命令行,獲取文件名並打開它(如何做到這一點取決於你的程序如何工作)。

#include <iostream> 

int main(int argc, char *argv[]) 
{ 
    for (int i = 1; i < argc; ++i) { 
     std::cout << "The " << i << "th argument is " << argv[i] << std::endl; 
    } 
} 

如果運行命令行此程序:如果您創建一個QApplication的,也可以通過QCoreApplications::arguments()訪問命令行參數

>test.exe "path/to/file" "/path/to/second/file" 
The 1th argument is path/to/file 
The 2th argument is /path/to/second/file 

在Qt。

您可能想在創建主窗口後加載文件。你可以做這樣的事情:

#include <QApplication> 
#include <QTimer> 

#include "MainWindow.h" 

int main(int argc, char *argv[]) 
{ 
    QApplication app(argc, argv); 
    MainWindow window; 

    QTimer::singleShot(0, & window, SLOT(initialize())); 

    window.show(); 

    return app.exec(); 
} 

這樣插槽MainWindow::initialize()(你必須定義),即會爲事件循環已經開始調用。

void MainWindow::initialize() 
{ 
    QStringList arguments = QCoreApplication::arguments(); 
    // Now you can parse the arguments *after* the main window has been created. 
} 
+0

在我的項目中,我們已經照顧了windows文件關聯部分,我只需要添加命令行參數處理。在Qt應用程序生命週期中觸發這個動作完全不清楚:在'window.show()'之後的'main'內或者在窗口中有一些'onLoad'事件...或者是什麼???這個答案讓我走上了正確的軌道。謝謝! – aldo

0

如果我正確理解你的問題,L2P.exe是你創建的一個Qt程序,你想要處理一個傳遞的參數作爲指定一個文件打開。如果是這樣的話,你只需要在你的main()方法中讀取這個參數並處理它。 (這不是自動發生的。)類似下面的,雖然你明明想增加一點錯誤檢查:

int main(int argc, char *argv[]) { 
    QApplication a(argc, argv); 

    const QStringList arguments = a.arguments(); 

    // The final argument is assumed to be the file to open. 
    if (arguments.size() > 1 && QFile::exists(arguments.last())) { 
    your_app_open(arguments.last()); 
    } 

    // ... etc. 
} 
相關問題