以下內容為本人的學習筆記,如需要轉載,請宣告原文鏈接 微信公眾號「englyf」https://mp.weixin.qq.com/s/z_JlmNe6cYldNf11Oad_JQ
先說明一下測驗環境
編譯器:vs2017x64
開發環境:Qt5.12
這里主要是總結一下,怎么在 QML 檔案中參考 C ++ 檔案里定義的內容?
很簡單,我們可以在 C ++ 檔案中通過 QML 引擎(QQmlEngine class)的背景關系物件(QQmlContext)呼叫方法 setContextProperty 設定對應的參考即可,詳情看看下面的方法宣告:
void QQmlContext::setContextProperty(const QString &name, QObject *value);
void QQmlContext::setContextProperty(const QString &name, const QVariant &value);
可以看到,既可以設定 QObject 型別的物件(指標),也可以設定 QVariant 兼容的型別資料(包括基本型別資料等)到 QML 引擎的背景關系中,然后在 QML 中就可以通過參考名 name 直接呼叫即可,
1. 設定型別資料
// main.cpp
#include <QDateTime>
void main() {
//...
QQmlEngine engine;
QDateTime dateTime = QDateTime::currentDateTime();
engine.rootContext()->setContextProperty("dateTime", &dateTime);
//...
}
以上代碼中直接將 QDateTime 型別的資料設定到引擎背景關系中,
Rectangle {
id: window
//...
Text {
text: dateTime
}
}
通過參考名 dateTime 將 C ++ 檔案中的資料系結到組件 Text 的 text 屬性上,進而顯示出來,
2. 設定物件指標
上面是設定資料,這里設定的是 QObject 型別的指標,所以在 QML 里還可以呼叫 C ++ 檔案中定義的物件,包括屬性和方法等,
首先,定義一個 QObject 的派生類 ApplicationData,從 QObject 派生是必須的,
// applicationdata.h
#include <QObject>
#include <QDateTime>
#include <QTimer>
class ApplicationData : public QObject
{
Q_OBJECT
public:
ApplicationData(){
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &ApplicationData::slt_timeout);
timer->start(1000);
}
Q_INVOKABLE QDateTime getCurrentDateTime() const {
return m_currentDateTime;
}
signals:
void sig_dataTimeUpdated();
private slots:
void slt_timeout() {
m_currentDateTime = QDateTime::currentDateTime();
emit sig_dataTimeUpdated();
}
private:
QDateTime m_currentDateTime;
};
其中 Q_INVOKABLE 用于宣告此方法可被元物件系統呼叫,這個類實作每 1000 ms 重繪內部日期時間屬性,并且發射信號 sig_dataTimeUpdated,此屬性值可以通過呼叫定義的公共方法 getCurrentDateTime() 得到,
下面再來定義程式入口檔案:
// main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "applicationdata.h"
int main(int argc, char *argv[])
{
qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
ApplicationData data;
engine.rootContext()->setContextProperty("currentDateTime", &data);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
在 QML 引擎裝載 QML 檔案前,先將類 ApplicationData 的物件指標設定到背景關系中,
下面再看看怎么呼叫指標對應的類物件,
// main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.VirtualKeyboard 2.4
Window {
id: window
visible: true
title: qsTr("Hello World")
Text {
id: name_id
anchors.centerIn: parent
}
Connections {
target: currentDateTime
onSig_dataTimeUpdated: {
name_id.text = currentDateTime.getCurrentDateTime();
}
}
}
使用 Connections 連接資料物件 currentDateTime 的信號,當指標物件的信號 sig_dataTimeUpdated 發射出來時,呼叫方法 getCurrentDateTime() 并用結果設定組件 Text 的屬性 text,
顯示的效果是動態重繪時間日期資料的,這和在背景關系中設定型別資料不同(不會重繪),如下圖:

其實在我的另一篇博文《一文入門Qt Quick》中也有對這一塊主題的說明,不妨去看看吧!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523216.html
標籤:其他
上一篇:重塑影響力
