为什么我的 window 没有显示?

Why does my window not show?

我需要写一个GrabWindow,所以我从QQuickWindow推导出我的classGrabWindow

#include <QtQuickWidgets/QtQuickWidgets>
#include <QString>

class GrabWindow : public QQuickWindow {
    Q_OBJECT
public:
    explicit GrabWindow(QQuickWindow *parent = nullptr);

public slots:
    void capture(QString const &path);
};
// .CPP
#include "grab_window.h"
#include <QImage>

GrabWindow::GrabWindow(QQuickWindow *parent) : QQuickWindow(parent) {

}

void GrabWindow::capture(const QString &path) {
    QImage img = this->grabWindow();
    img.save(path);
}

我在QML中注册后:qmlRegisterType<GrabWindow>("myapp", 1, 0, "GrabWindow"); 在我在 QML 中定义 window 之后:

import QtQuick 2.4
import QtQuick.Controls 2.2
import QtQuick.Window 2.3
import myapp 1.0

GrabWindow {
    id : translationWindow
    width : 1024
    height : 768
    color: "transparent"
    visibility: "FullScreen"
    visible: true;
    signal capture(string path)

    MouseArea {
        anchors.fill: parent
        onClicked: translationWindow.capture("/home/user/saveTest.jpg")
    }
}

但是开始时不显示(我知道它是透明的,我的意思是抓取 window 不开始显示)。如果我使用 WindowApplicationWindow 而不是 GrabWindow 那么一切正常我看到透明的全屏 window.
怎么了?

您的 GrabWindow 未显示,因为当您设置 visible 属性 时,它与您使用 Windowvisible 属性.

你的只是 QWindowvisible 属性。 Window 不直接实例化 QQuickWindow,它实例化了一个私有 Qt class QQuickWindowImpl,它用一个自定义的 visible 属性 覆盖了 visible 属性。 它似乎延迟了 QWindow::setVisible 的实际调用。

因此,我不认为 QQuickWindow 应该继承自。您可以尝试在 Component.onCompleted 中执行 visible = true,但我不确定它是否能解决您的问题。

我建议你的不是 subclassing QQuickWindow,而是创建一个新类型并将现有的 Window.

传递给它

可能 API 可能是:

Window {
    id: myWindow
    //...
    MouseArea {
        anchors.fill: parent
        onClicked: WindowGrabber.grab(myWindow, path) //singleton type
    }
}

Window {
    id: myWindow
    //...
    WindowGrabber { // regular type
        id: windowGrabber
        window: myWindow
    }
    MouseArea {
        anchors.fill: parent
        onClicked: windowGrabber.grab(path) // you could even add a path property in WindowGrabber and not have it as a function parameter if that makes sense for your use case
    }
}