QT在QWidget中加载qml界面
本文简要介绍在MainWindowt中加载qml文件,并通过信号与槽实现双向交互。
开发环境:
- Qt5.12.1
- Qt Creator 4.8.1
- 编译器 VS 2017 64位
创建Qt Widget Applicition
- 创建Qt Widget Applicition 取名为WidgetAndQml;
- 选择MSVC 2017 64bit编译器;
- 继承QMainWindow,勾选创建界面文件;
- 在工程文件.pro中添加quickwidgets和qml;
QT += core gui quickwidgets qml
- 在.ui文件拖入QLineEdit、QPushButton和QQuickWidget控件,并简单布局。
准备QML文件
- 在工程中添加新文件,选择QML File,取名为myqml;
- 在myqml文件中添加代码。
import QtQuick 2.0
Rectangle{
id: root
width: 400
height: 300
Text {
id: text
anchors.centerIn: parent
color: "red"
font{pixelSize: 30}
text: qsTr("Hello World")
}
}
显示QML
-
将QML文件添加到资源文件中;
-
在Mainwindow中添加代码,其中QUrl路径为你的qml界面文件路径;
this -> ui -> quickWidget ->setFocus();
this -> ui -> quickWidget -> setResizeMode(QQuickWidget::SizeRootObjectToView);
this -> ui -> quickWidget -> setSource(QUrl("qrc:/qml/myqml.qml"));
- 最终运行效果可以看文末图片。
实现MainWindow与Qml简单交互
两者可以通过信号与槽实现交互。
- 在mainwindow.h中定义信号sendToQml用于发送LineEdit中的内容,当点击mainwindow界面中的按钮,就会发送该信号,信号的参数为LineEdit中的内容。定义槽函数receiveFromQml用于连接myqml中的信号,槽函数receiveFromQml的实现就是在控制台中qDebug出qml信号传来的数据
private slots:
void receiveFromQml(QString str);
signals:
void sendToQml(QString str);
void MainWindow::on_pushButton_clicked()
{
emit sendToQml(this -> ui -> lineEdit -> text());
}
void MainWindow::receiveFromQml(QString str)
{
qDebug() << str;
}
- 在myqml文件中添加信号;
import QtQuick 2.0
Rectangle{
id: root
width: 400
height: 300
signal receiveText(string str)
signal sendText(string str)
Text {
id: text
anchors.centerIn: parent
color: "red"
font{pixelSize: 30}
text: qsTr("Hello World")
}
MouseArea{
anchors.fill: parent
onClicked: root.sendText(text.text)
}
onReceiveText: text.text = str
}
- 连接信号与槽。在MainWindow的构造函数中添加如下代码:
QQuickItem *item = this -> ui -> quickWidget ->rootObject(); //需要包含头文件 QQuickItem
connect(this,SIGNAL(sendToQml(QString)),item,SIGNAL(receiveText(QString))); //信号与信号连接,信号的实质就是函数
connect(item,SIGNAL(sendText(QString)),this,SLOT(receiveFromQml(QString)));
实现效果
1.直接运行;
2. 在LineEdit中添加,然后点击按钮发送,可以看到Hello World变成Hello;
3.点击quickwidget,发现控制台有输出。
能力有限,如有错误请大家指教!
源码:https://download.csdn.net/download/qq_43015524/12040419
参考文章
https://blog.csdn.net/liang19890820/article/details/77044117