當您在文件雙擊文件名作爲命令傳遞對相關程序的行參數。你必須解析命令行,獲取文件名並打開它(如何做到這一點取決於你的程序如何工作)。
#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.
}
在我的項目中,我們已經照顧了windows文件關聯部分,我只需要添加命令行參數處理。在Qt應用程序生命週期中觸發這個動作完全不清楚:在'window.show()'之後的'main'內或者在窗口中有一些'onLoad'事件...或者是什麼???這個答案讓我走上了正確的軌道。謝謝! – aldo