【Qt】Qml界面中嵌入C++ Widget窗口
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文件
- 这里的
titile
的Helllo 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窗口句柄竟然是这样获取