在本页

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 中的文件或将文件拖动到应用程序的 Dock 图标,或在 iOS 上从其他应用程序共享文件。

该事件仅用于向应用程序发出请求通知。如果文件不应被打开,则可以安全地忽略它。

苹果平台

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

例如,以下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>LSItemContentTypes</key>
            <array>
                <string>public.png</string>
            </array>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
        </dict>
    </array>
</dict>
</plist>

在 iOS 系统中,也需要使用以下密钥,应用程序才能在 "文件 "应用程序中显示为 "用打开 "操作:

<key>UISupportsDocumentBrowser</key>
<true/>

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

#include <QApplication>
#include <QDebug>
#include <QFile>
#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

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

© 2026 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.