在 C++ 代码中使用 qml 类型作为 QWindow [英] Using a qml type as a QWindow in C++ code

查看:22
本文介绍了在 C++ 代码中使用 qml 类型作为 QWindow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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
    }
}

这篇关于在 C++ 代码中使用 qml 类型作为 QWindow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆