QQuickWidget与qml交互的第二种方式便是注册qml类型,即使用qmlRegisterType注册一个QObject派生类到qml中。
qmlRegisterType的官方描述如下:
This template function registers the C++ type in the QML system with the name qmlName, in the library imported from uri having the version number composed from versionMajor and versionMinor.
该模板函数在从uri导入的,具有由versionMajor和versionMinor组成的版本号的库中,以qmlName在QML系统中注册C ++类型。
函数定义如下:
int qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName)
- char *uri:qml中import的内容
- versionMajor:主版本号
- versionMinor:次版本号
- qmlName:qml中实例的类名
注册qml类型中可以分为两种,注册属性和方法
- 属性:使用Q_PROPERTY注册的属性
- 方法:注册为public slots或是标记为Q_INVOKABLE
下面的代码中分别展示了上述两种获取数据的方法
#include <QObject>
#include <QDateTime>
class testObject : public QObject
{
Q_OBJECT
// 注册属性,通过Q_PROPERTY注册到元对象系统
Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged)
public:
testObject(QObject *parent = Q_NULLPTR)
{
};
~testObject() { };
void setName(const QString &name)
{
m_name = name;
emit nameChanged(name);
}
QString getName()
{
return m_name;
}
// 注册方法, 使用Q_INVOKABLE来修饰成员函数,目的在于被修饰的成员函数能够被元对象系统所唤起
Q_INVOKABLE QDateTime getCurrentDateTime()
{
return QDateTime::currentDateTime();
}
signals:
void nameChanged(const QString name);
private:
QString m_name = "Initial Text";
};
#include "widget.h"
#include "ui_widget.h"
#include "testObject.h"
#include <QQmlContext>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
qmlRegisterType<testObject>("com.qt.testcomponent", 1, 0, "TestData");
ui->quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
}
Widget::~Widget()
{
delete ui;
}
import QtQuick 2.9
import QtQuick.Window 2.2
import com.qt.testcomponent 1.0
Item {
visible: true
width: 640
height: 480
Rectangle {
id: bg1;
width: parent.width;
height: 50;
radius: height / 8;
color: "blue";
anchors.top: parent.top;
Text {
id: namer;
// 通过注册属性获取到的数据
text: testData.name;
font.pixelSize: 30
anchors.centerIn: bg1;
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: {
if(mouse.button === Qt.LeftButton){
testData.name = "Mouse Clicked!";
console.log(testData.name);
}
}
}
}
Rectangle {
id: bg2;
width: parent.width;
height: 50;
radius: height / 8;
color: "purple";
anchors.top: bg1.bottom;
anchors.topMargin: 10;
Text {
id: timer;
// 通过注册方法获取到的数据
text: testData.getCurrentDateTime();
font.pixelSize: 30
anchors.centerIn: bg2;
}
}
// 注意实例化导入的类型
TestData {
id: testData;
}
}