Qt C++中引用 qml文件
习惯了Qt gui C++ 编程的人,都会觉得QWidget真是一个很方便的东西。现阶段,qml已经很流行了,qml也有其很多特有的亮点,如炫酷的动画效果,简洁快速的页面编程。那么,作为一个传统的gui C++ 玩家,该如何引入qml呢?下面简单说明一种方法。
通过 QQuickWidget 引用qml文件
QQuickWidget 的详细描述请参考qt助手中的描述。
使用步骤
1. .pro文件中加入模块 quick 和 quickwidgets
QT += quick
QT += quickwidgets
2. 实例化QQuickWidget后,调用QQuickWidget的setSource()函数,设置qml源文件。
QQuickWidget *wid = new QQuickWidget(this);
wid->setSource(QUrl(QStringLiteral("qrc:/qml/ClickCount.qml"))); //注意路径
(这里踩了一个坑:记得要先创建资源文件,并且在资源文件中添加qml文件,否则最后运行的时候,老是报错:找不到qml文件。类似如下:)
3.就可以显示qml的内容、读取、设置qml的属性啦。
例子:
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
private slots:
void clearCount(int count);
void textChange(QString str);
signals:
void testSignal(QString);
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QQuickWidget>
#include <QQuickItem>
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//使用QQuickWidget调用qml
QQuickWidget *wid = new QQuickWidget(this);
wid->setSource(QUrl(QStringLiteral("qrc:/qml/ClickCount.qml")));
wid->setResizeMode(QQuickWidget::SizeRootObjectToView);
wid->show();
//获取qml根元素
QQuickItem *item = wid->rootObject();
//读取qml的属性
qDebug()<<item->property("count").toInt();
qDebug()<<item->property("showText").toString();
//设置qml属性
item->setProperty("count", 100);
//修改qml中根元素的子元素的属性
QObject *objTitle = item->findChild<QObject *>("title"); //利用元素的objectName来查找
if(objTitle)
{
objTitle->setProperty("text", "标题已修改");
}
//连接qml的信号
connect(item, SIGNAL(clearCount(int)), this, SLOT(clearCount(int)));
connect(item, SIGNAL(textChange(QString)), this, SLOT(textChange(QString)));
}
Widget::~Widget()
{
delete ui;
}
void Widget::clearCount(int count)
{
qDebug()<<"clearCount: "<<count;
}
void Widget::textChange(QString str)
{
qDebug()<<"textChange: "<<str;
}
ClickCount.qml
import QtQuick 2.0
Item {
id: root
objectName: "clickCount"
width: 400; height: 400
property int count: 0
property string showText: txt.text
signal textChange(string str)
signal clearCount(int c)
Rectangle {
anchors.fill: parent
color: "darkgrey"
//清空次数按钮
Rectangle {
width: 100; height: 30
x:0; y:0
border.color: "black"
border.width: 1
Text {
text: "次数清零"
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
root.count = 0
root.clearCount(root.count)
}
}
}
//标题
Text {
id: title
objectName: "title"
text: "点击计数器"
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: parent.top
anchors.topMargin: 20
}
//计数显示
Rectangle {
width: 200
height: 200
anchors.centerIn: parent
color: "darkseagreen"
Text {
id: txt
text: "点击次数" + count
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
count += 1
root.textChange(txt.text)
}
}
}
}
}
运行效果图: