【Qt】Qml界面中嵌入C++ Widget窗口

55 篇文章 1 订阅

1. 目的

qml做出的界面漂亮,但是执行效率低,一直想找一个方法实现qml中嵌入c++界面。现在从网上找到一个方法,简单试了一下貌似可行,分享一下。

2. 显示效果

在这里插入图片描述

3. 代码

3.1 工程结构

在这里插入图片描述

3.2 pro文件

  • 需要添加widgets => QT += quick widgets
QT += quick widgets

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
        main.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

3.3 main.cpp文件(重点)

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QWindow>
#include <QtWidgets/QWidget>
#include <QPushButton>
#include <QApplication>

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QApplication app(argc, argv);	//这里改为QApplication 

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
        &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
    engine.load(url);

    //获取QML源窗口
    QObject *QmlObj = engine.rootObjects().first();
    QWindow *QmlWindow = qobject_cast<QWindow *>(QmlObj);
    QmlWindow->setTitle("C++ set title");
    WId parent_HWND = QmlWindow->winId();

    //新建widget
    QWidget widget;
    widget.setGeometry(0, 0, 300, 300);
    QPushButton btn("send", &widget);
    btn.setGeometry(5, 5, 60, 20);
    widget.winId();

    //将widget插入QML
    widget.windowHandle()->setParent(QmlWindow);
    widget.show();

    return app.exec();
}

3.4 main.qml文件

  • 这里的titileHelllo World被c++修改了
import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
}

4. 参考

震惊!QWidget竟然可以嵌入到QML中,QMl窗口句柄竟然是这样获取

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值