QFileOpenEvent Class

QFileOpenEvent 类提供了一个在请求打开文件或 URL 时发送的事件。更多

Header: #include <QFileOpenEvent>
CMake.QFileOpenEvent find_package(Qt6 REQUIRED COMPONENTS Gui)
target_link_libraries(mytarget PRIVATE Qt6::Gui)
qmake: QT += gui
继承: QEvent

公共函数

QString file() const
QUrl url() const

详细说明

当操作系统要求打开一个文件或 URL 时,文件打开事件将被发送至QApplication::instance() 。这是一个高级事件,可由不同的用户操作引起,具体取决于用户的桌面环境;例如,在 macOS 上双击 Finder 中的文件图标。

该事件仅用于向应用程序发出请求通知。它可以被安全地忽略。

注意: 该类目前仅支持 macOS。

macOS 示例

要在 macOS 上触发该事件,必须对应用程序进行配置,让操作系统知道它应该对哪类文件做出反应。

例如,下面的Info.plist 文件声明应用程序可以作为扩展名为 PNG 的文件的查看器:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>png</string>
            </array>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
        </dict>
    </array>
</dict>
</plist>

以下QApplication 子类的实现展示了如何处理 QFileOpenEvent 以打开掉落在应用程序 Dock 图标上的文件。

#include <QApplication>
#include <QDebug>
#include <QFileOpenEvent>
#include <QPushButton>

class MyApplication : public QApplication
{
public:
    MyApplication(int &argc, char **argv)
        : QApplication(argc, argv)
    {
    }

    bool event(QEvent *event) override
    {
        if (event->type() == QEvent::FileOpen) {
            QFileOpenEvent *openEvent = static_cast<QFileOpenEvent *>(event);
            const QUrl url = openEvent->url();
            if (url.isLocalFile()) {
                QFile localFile(url.toLocalFile());
                // read from local file
            } else if (url.isValid()) {
                // process according to the URL's schema
            } else {
                // parse openEvent->file()
            }
        }

        return QApplication::event(event);
    }
};

请注意,QFileOpenEvent::file() 并不保证是可使用QFile 打开的本地文件名。字符串的内容取决于源程序。

成员函数文档

QString QFileOpenEvent::file() const

返回应用程序应打开的文件名。

但不保证是本地文件的路径。

QUrl QFileOpenEvent::url() const

返回应用程序应打开的网址。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.