在 C++ 代码中使用 qml 类型作为 QWindow

2022-01-19 00:00:00 qt5 qt qml c++

我在 qtcreator 中创建了一个 MainWindow : public QMainWindow 和一个 qtquick ui 文件(用于工具箱).我希望工具箱在主窗口中显示为浮动子窗口.我正在尝试为此使用 QMdiArea .我看过的一个教程说我需要像这样向 QMdiArea 添加一个窗口:

I've created a MainWindow : public QMainWindow and a qtquick ui file (for a toolbox) in qtcreator. I want the toolbox to appear as a floating subwindow in mainwindow. I'm trying to use QMdiArea for that. A tutorial I've seen says that I need to add a window to the QMdiArea like this:

mdi->addSubWindow(win);

其中 win 是一个 QWidget.如何在我的 C++ 代码中使用使用 qml 创建的工具箱?

where win is a QWidget. How do I use the toolbox created with qml in my C++ code?

推荐答案

你可以使用QQuickWidget,但是要记住QML的根必须是Item或者继承自Item的类,不能是Window或者ApplicationWindow.

You can use QQuickWidget but remember that the root of the QML must be an Item or a class that inherits from the Item, it can not be Window or ApplicationWindow.

#include <QApplication>
#include <QMainWindow>
#include <QMdiArea>
#include <QQuickWidget>

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

    QApplication app(argc, argv);
    QMainWindow w;
    QMdiArea *mdiarea = new QMdiArea;
    w.setCentralWidget(mdiarea);
    QQuickWidget *toolbar = new QQuickWidget(QUrl("qrc:/main.qml"));
    toolbar->setResizeMode(QQuickWidget::SizeRootObjectToView);
    mdiarea->addSubWindow(toolbar);
    w.show();
    return app.exec();
}

ma??in.qml

import QtQuick 2.9
import QtQuick.Controls 2.4

Rectangle {
    visible: true
    width: 640
    height: 480
    color: "red"
    Button{
        text: "Stack Overflow"
        anchors.centerIn: parent
    }
}

相关文章