QML知識 與Qt資料互動

2021-09-03 10:28:21 字數 1771 閱讀 2895

使用qml程式設計時,常常會與qt之間進行資料訪問或修改,本篇文章是介紹qt與qml的資料互動方法,一般有兩種方法。

testmodel標頭檔案:

#ifndef testmodel_h

#define testmodel_h

#include class testmodel : public qobject

qstring text() 

void settext(qstring text) 

signals:

void statuschanged();

private:

qstring m_text;

};#endif // testmodel_h

main函式:

int main(int argc, char *argv)

(1) 例:

qmlregistertype("testmodel", 1, 0, "testmodel");
(2) qml中使用方法:

testmodel 

column 

}mousearea

(2) 通過qml建立控制項一樣建立例項來訪問或修改資料;

(3) testmodel為繼承qobject的c++物件,通過訪問或修改testmodel的text來達到程式的目的。

(1) 例:

engine.rootcontext()->setcontextproperty("testmodel", new testmodel());

(2) qml中使用方法:

<1> qml檔案執行匯入命令

import testmodel 1.0
<2> 使用

column 

}mousearea

(3) 在程式建立qml資源時設定全域性訪問物件"testmodel", 示例的字串首字母只能下或線或者是小寫。

(1) 它們的資料互動通過q_property巨集定義實現

q_property(qstring text read text write settext notify statuschanged)
(2) 當qml訪問資料(呼叫testmodel.text)時,qt端則會呼叫text函式返回乙個值。這裡測試程式是:

qstring text()
(3) 當需要修改資料時候(呼叫testmodel.text="123")時,qt端則會呼叫settext設定相應的行為。這裡測試程式是:

void settext(qstring text)
(4) 由於q_property巨集定義類statuschanged訊號,當用於傳送statuschanged訊號時,text()函式則會自動呼叫,從而重新整理text的值(這裡測試程式返回了固定值"123")。如果text函式返回的是m_text,這是settext設定的值。

qstring text()
(1) 方法1需要建立例項才能使用,而方法2則是只有乙個全域性例項,在setcontextproperty就已經建立了;

(2) 方法1學要在qml的import匯入, 如下例(testmodel為註冊的字串,1.0為註冊定義的版本號);

import testmodel 1.0
(3) 方法1生命週期在本頁面,方法2生命週期是全域性;

qml與C 的互動

簡單說下我自己對qml與c 的互動的理解流程 1.介面互動,很多新手可能會寫qt介面或者qml介面,但想要把qml與c 結合起來就一臉矇逼了。首先我提供個簡單的方法實現qml和c 的介面互動,首先引入幾個重要的標頭檔案,當然在專案檔案中需要加qt quickwidgets才能引用以下標頭檔案 inc...

QML如何與C 互動

大家都知道,qml作為構建介面的語言是非常簡潔的,但是介面的後台有些時候是經常要與c 互動的,那麼這個時候,如何與c 進行互動就尤為重要了,在這裡就需要用到 template int qmlregistertype const char uri,int versionmajor,int versio...

qml與C 的互動

qml與c 的互動,簡單說下我自己對qml與c 的互動的理解流程 1.介面互動,很多新手可能會寫qt介面或者qml介面,但要把qml與c 結合起來就一臉矇逼了。首先我提供個簡單的方法實現qml和c 的介面互動。首先引入幾個重要的標頭檔案 include include include widget ...