解析终端参数Qt Mac OS X.

时间:2013-07-10 05:11:59

标签: c++ macos qt terminal

我有一个简单的文本编辑器,我想在系统文件管理器中双击它时打开一个文件。

我在Ubuntu Linux(13.04)下成功地做到了这一点,但在Mac OS X中,我的代码无效。

经过研究后,我发现你需要在终端中添加--args参数,以便将参数解析为main()

我修复了我的代码,现在我的应用程序包可以从终端打开文件,但是当我在Finder中双击文件(并选择我的应用程序)时,我的应用程序启动就好像没有收到任何终端参数(创建一个新的文件)。

以下是main()函数的代码:

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

    Textpad.setApplicationName("MyApp");
    Textpad.setApplicationVersion("0.7.2");

    Textpad.setWindowIcon(QIcon(":/app-icon/48x48/icon.png"));

    MainWindow *Window = new MainWindow();

    QString Arguments;
    QString FileLocation;

    if (argc != 1) {
        int i;
        for (i = 0; i < argc; i++)
            Arguments = argv[i];

        // Check if the OS is Mac OS X (Mac OS X is 3)
        if (Window->CheckOS() == 3)
            // Remove the "--args" so that we don't confuse it with the file location
            Arguments.replace("--args", "");

        if (Arguments == "--help") {
            // Show help
        }

        // Create a new file when Textpad is launched normally (under Linux)
        if (Arguments == "%U") {
            FileLocation.clear();
            // Load settings and create UI
            Window->Initialize();
            // Open the requested file
            Window->LoadFile(FileLocation);
        }

        else {
            FileLocation = Arguments;
            // Load settings and create UI
            Window->Initialize();
            // Open the requested file
            Window->LoadFile(FileLocation);   
        }
    }

    else {
        // Create new file
        FileLocation.clear();
        // Load settings and create UI
        Window->Initialize();
        // Open the requested file
        Window->LoadFile(FileLocation);
    }

    return MyApp.exec();
}

正如我之前所说的,当我写下以下文件时,我的应用程序打开了没有来自终端的问题的文件:

open MyApp.app --args <location of my file>

但是当我尝试从Finder打开文件时失败了。

我缺少什么?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

首先,您必须链接到OX-X Framework。 OSX适用于类似于信号槽的事件。文件名也将由apple事件给出。我很久以前就用另一种语言做了这个,但我仍然找到了一个参考:

现在在Qt存档中编辑doc: https://doc.qt.io/archives/qq/qq12-mac-events.html