如何拦截和取消窗口的最小化?

Mus*_*sis 14 qt qml qwindow

我的Window项目中有一个子类,在运行时,实例创建并完全在QML端显示.我知道我可以阻止窗口由不包括被最小化WindowMinimizeButtonHintflags:,但我确实需要有最小化按钮存在并启用,但能够拦截的最小化按钮点击,取消实际的最小化,并做其他事(仅供参考我的客户要求这种非标准的窗口行为,而不是我.

到目前为止,我已经能够达到的唯一的事情是处理onWindowStateChanged:事件,检查windowState === Qt.WindowStateMinimized并呼吁show()从一个计时器(它调用的事件处理程序内直接什么都不做).这导致窗口向下移动到系统托盘,然后突然恢复正常.

有没有办法做到这一点,比如OnMinimized可以取消的事件?

编辑:根据Benjamin T的回答,我至少是OSX解决方案的一部分:

#import <AppKit/AppKit.h>

bool NativeFilter::nativeEventFilter(const QByteArray &eventType, 
    void *message, long *result)
{
    if (eventType == "mac_generic_NSEvent") {
        NSEvent *event = static_cast<NSEvent *>(message);
        if ([event type] == NSKeyDown) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我能够拦截并取消所有NSKeyDown事件(同时留下其他事件,如鼠标点击等仍在工作).剩下的问题是我仍然不知道拦截一个最小化事件 - NSEvent.h似乎没有任何涵盖它的东西.也许我需要演绎不同类型的活动?

编辑2 - 工作解决方案:

我无法找到任何方法来截取最小化事件并取消它,所以我的解决方法是拦截窗口上的点击,确定点击是否超过最小化按钮(或关闭或缩放按钮)并取消如果是这样的事件(并向我的qml窗口发送通知,表示发生了点击).我还处理双击标题栏以缩放窗口,并使用Command-M键最小化窗口的情况.

第一步是实施一个QAbstractNativeEventFilter.在你的标题中:

#include <QAbstractNativeEventFilter>

class NativeFilter : public QAbstractNativeEventFilter {
public:
    bool nativeEventFilter(const QByteArray &eventType, void *message, 
        long *result);
};
Run Code Online (Sandbox Code Playgroud)

实施:

#import <AppKit/AppKit.h>
#import <AppKit/NSWindow.h>
#import <AppKit/NSButton.h>

bool NativeFilter::nativeEventFilter(const QByteArray &eventType, void 
    *message, long *result)
{
    if (eventType == "mac_generic_NSEvent") {

        NSEvent *event = static_cast<NSEvent *>(message);
        NSWindow *win = [event window];

        // TODO: determine whether or not this is a window whose
        // events you want to intercept. I did this by checking
        // [win title] but you may want to find and use the 
        // window's id instead.

        // Detect a double-click on the titlebar. If the zoom button 
        // is enabled, send the full-screen message to the window
        if ([event type] == NSLeftMouseUp) {
            if ([event clickCount] > 1) {
                NSPoint pt = [event locationInWindow];
                CGRect rect = [win frame];
                // event coordinates have y going in the opposite direction from frame coordinates, very annoying
                CGFloat yInverted = rect.size.height - pt.y;
                if (yInverted <= 20) {
                    // TODO: need the proper metrics for the height of the title bar

                    NSButton *btn = [win standardWindowButton:NSWindowZoomButton];
                    if (btn.enabled) {

                        // notify qml of zoom button click

                    }

                    return true;
                }
            }
        }

        if ([event type] == NSKeyDown) {

            // detect command-M (for minimize app)
            if ([event modifierFlags] & NSCommandKeyMask) {

                // M key
                if ([event keyCode] == 46) {
                    // notify qml of miniaturize button click
                    return true;
                }

            }

            // TODO: we may be requested to handle keyboard actions for close and zoom buttons. e.g. ctrl-cmd-F is zoom, I think,
            // and Command-H is hide.

        }


        if ([event type] == NSLeftMouseDown) {

            NSPoint pt = [event locationInWindow];
            CGRect rect = [win frame];

            // event coordinates have y going in the opposite direction from frame coordinates, very annoying
            CGFloat yInverted = rect.size.height - pt.y;

            NSButton *btn = [win standardWindowButton:NSWindowMiniaturizeButton];
            CGRect rectButton = [btn frame];
            if ((yInverted >= rectButton.origin.y) && (yInverted <= (rectButton.origin.y + rectButton.size.height))) {
                if ((pt.x >= rectButton.origin.x) && (pt.x <= (rectButton.origin.x + rectButton.size.width))) {

                    // notify .qml of miniaturize button click

                    return true;
                }
            }

            btn = [win standardWindowButton:NSWindowZoomButton];
            rectButton = [btn frame];

            if (btn.enabled) {
                if ((yInverted >= rectButton.origin.y) && (yInverted <= (rectButton.origin.y + rectButton.size.height))) {
                    if ((pt.x >= rectButton.origin.x) && (pt.x <= (rectButton.origin.x + rectButton.size.width))) {

                        // notify qml of zoom button click

                        return true;
                    }
                }
            }

            btn = [win standardWindowButton:NSWindowCloseButton];
            rectButton = [btn frame];
            if ((yInverted >= rectButton.origin.y) && (yInverted <= (rectButton.origin.y + rectButton.size.height))) {
                if ((pt.x >= rectButton.origin.x) && (pt.x <= (rectButton.origin.x + rectButton.size.width))) {

                    // notify qml of close button click

                    return true;
                }
            }

        }

        return false;

    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

然后在main.cpp中:

Application app(argc, argv);
app.installNativeEventFilter(new NativeFilter());
Run Code Online (Sandbox Code Playgroud)

Ben*_*n T 5

一般而言,您应该使用事件系统而不是信号/插槽来拦截事件和更改。

这样做的最简单方法是将您使用的对象子类化并重新实现适当的事件处理程序,或者使用事件过滤器。

由于您正在使用QML,因此子类化可能很困难,因为您无法访问所有Qt内部类。

使用事件过滤时,代码如下所示。

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);


    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    if (engine.rootObjects().isEmpty())
        return -1;

    auto root = engine.rootObjects().first();
    root->installEventFilter(new EventFilter());

    return app.exec();
}

class EventFilter : public QObject
{
    Q_OBJECT
public:
    explicit EventFilter(QObject *parent = nullptr);
    bool eventFilter(QObject *watched, QEvent *event) override;
};

bool EventFilter::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::WindowStateChange) {
        auto e = static_cast<QWindowStateChangeEvent *>(event);
        auto window = static_cast<QWindow *>(watched);

        if (window->windowStates().testFlag(Qt::WindowMinimized)
                && ! e->oldState().testFlag(Qt::WindowMinimized))
        {
            // Restore old state
            window->setWindowStates(e->oldState());
            return true;
        }
    }

    // Do not filter event
    return false;
}
Run Code Online (Sandbox Code Playgroud)

但是,您将很快遇到与使用信号/插槽机制相同的问题:Qt仅在窗口已最小化时通知您。意味着此时恢复窗口将产生隐藏/显示效果。

因此,您需要更深入地了解本机事件过滤器。

以下代码在Windows上有效,您应该将其适配于macOS:

class NativeFilter : public QAbstractNativeEventFilter {
public:
    bool nativeEventFilter(const QByteArray &eventType, void *message, long *result);
};

bool NativeFilter::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
/* On Windows we interceot the click in the title bar. */
/* If we wait for the minimize event, it is already too late. */
#ifdef Q_OS_WIN
    auto msg = static_cast<MSG *>(message);
    // Filter out the event when the minimize button is pressed.
    if (msg->message == WM_NCLBUTTONDOWN && msg->wParam == HTREDUCE)
        return true;
#endif

/* Example macOS code from Qt doc, adapt to your need */
#ifdef Q_OS_MACOS
    if (eventType == "mac_generic_NSEvent") {
        NSEvent *event = static_cast<NSEvent *>(message);
        if ([event type] == NSKeyDown) {
            // Handle key event
            qDebug() << QString::fromNSString([event characters]);
        }
}
#endif

    return false;
}
Run Code Online (Sandbox Code Playgroud)

在您的main()中:

QGuiApplication app(argc, argv);
app.installNativeEventFilter(new NativeFilter());
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以阅读有关的Qt文档QAbstractNativeEventFilter

您可能需要使用QWindow::winId()检查本机事件的目标窗口。

由于我不是macOS开发人员,所以我不知道该怎么办NSEvent。此外,它似乎NSWindowDelegate类可能对您有用:https://developer.apple.com/documentation/appkit/nswindowdelegate 如果你可以检索NSWindowQWindow::winId(),你应该能够使用它。