Qt - 双击打开自定义文件

2 windows qt loading

我有一个程序和一个带有一些信息行的.l2p文件.我运行了一个注册表文件:

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\""
Run Code Online (Sandbox Code Playgroud)

当我双击.l2p文件时,程序启动但不加载文件.我需要做些什么才能使其正确加载?示例代码将非常感激.

Cla*_*dio 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果从命令行运行此程序:

>test.exe "path/to/file" "/path/to/second/file"
The 1th argument is path/to/file
The 2th argument is /path/to/second/file
Run Code Online (Sandbox Code Playgroud)

在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();
}
Run Code Online (Sandbox Code Playgroud)

这样MainWindow::initialize(),一旦事件循环开始,就会调用插槽(您必须定义).

void MainWindow::initialize()
{
    QStringList arguments = QCoreApplication::arguments();
    // Now you can parse the arguments *after* the main window has been created.
}
Run Code Online (Sandbox Code Playgroud)