当您双击文件时,文件名将作为命令行参数传递给相关程序。您必须解析命令行,获取文件名并打开它(如何做到这一点取决于您的程序如何工作)。
#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;
}
}
如果你从命令行运行这个程序:
>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 中,如果您创建 QApplication,您还可以通过QCoreApplications::arguments()访问命令行参数。
您可能希望在创建主窗口后加载文件。你可以这样做:
#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.
}