【Qt】Qt C++ Widget中嵌入qml
1. 效果
2. 方法
- 使用
QQuickWidget
方式
QQuickWidget *view = new QQuickWidget;
view->setSource(QUrl::fromLocalFile("myqmlfile.qml"));
view->show();
- 除了
QQuickWidget
方式还可以使用QQuickView
方式,请自行查阅资料
3. 代码
3.1 工程目录
3.2 pro文件
备注:需要添加
quickwidgets
QT += core gui quickwidgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# 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 \
dialog.cpp
HEADERS += \
dialog.h
FORMS += \
dialog.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
DISTFILES +=
RESOURCES += \
res.qrc
3.3 main.cpp
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
3.4 dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
signals:
cppClick();
public slots:
void onQmlClick();
private slots:
void on_pushButton_clicked();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
3.5 dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
#include <QtQuickWidgets>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
//c++向qml中传数据
ui->quickWidget->rootContext()->setContextProperty("$color", "red");
//qml导入
QUrl source("qrc:/qmlFile.qml");
ui->quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
ui->quickWidget->setSource(source);
ui->quickWidget->setClearColor(QColor(Qt::transparent));
//qml与c++交互
QQuickItem* qmlItem = ui->quickWidget->rootObject();
connect(qmlItem, SIGNAL(qmlClick()), this, SLOT(onQmlClick()));
connect(this, SIGNAL(cppClick()), qmlItem, SLOT(onCppClick()));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::onQmlClick()
{
qDebug() << "this is C++: qml's click";
}
void Dialog::on_pushButton_clicked()
{
emit cppClick();
}
3.6 qmlFile.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
Item {
id: _mRoot
signal qmlClick();
function onCppClick()
{
console.log("this is qml: cpp's click")
}
Rectangle{
width: 200
height: 200
color: $color
border.color: "grey"
border.width: 1
Button{
width: 100
height: 50
text: "qml button"
anchors.centerIn: parent
onClicked: {
qmlClick();
}
}
}
}
3.7 dialog.ui
4. 参考
- Qt 之 QWidget嵌入Qml文件以及如何交互
- 通俗易懂玩QT:QQuickWidget学习