qt中c++與qml實現互動的兩種基本方式
(1)註冊上下文(將c++物件嵌入到帶有上下文屬性的qml中)
main.cpp:
#include
#include
#include"mytest.h" //包含三個基本的庫檔案以及類的標頭檔案
int main(intargc, char *argv)
mytest data; //定義乙個類物件
qquickview view;
view.rootcontext()->setcontextproperty("myobjectexposebycxproperty",&data);
view.setsource(qurl("qrc:/main.qml"));
view.show();
main.qml:
//注意使用註冊上下文的方式就不能使用系統自帶的視窗了
import qtquick2.3
import qtquick.controls1.0
item {
id:window
width: 800
height: 480
property bool flag: false //自定義定義全域性屬性
button{
id:mybtn
x:300
y:100
width:100
height:50
text:"ok"
onclicked: {
console.log("yes")
if(flag == false)
flag = true
else
flag = false
myobjectexposebycxproperty.setvalue()
textarea{
id:mytxt
x:300
y:50
width:100
height:40
text:"123456"
connections{
target: myobjectexposebycxproperty
onvaluechange:{
console.log("success")
mytxt.text = ( (flag == true)?"888":"666")
mytest.h:
#ifndef mytest_h
#define mytest_h
#include
class mytest: public qobject
q_object
public:
explicit mytest(qobject *parent = 0);
signals:
void valuechange();
public slots:
void setvalue();
private:
int m_data;
#endif //mytest_h
mytest.cpp:
#include"mytest.h"
mytest::mytest(qobject*parent) :
qobject(parent)
void mytest::setvalue()
emit valuechange();
(2)註冊c++類為qml型別
main.cpp
#include
#include"mytesttwo.h"
int main(intargc, char *argv)
qmlregistertype("org.com.mytest",1,0,"mytest");
engine.load(qurl(qstringliteral("qrc:/main.qml")));
mytesttwo.cpp:
#include"mytesttwo.h"
mytesttwo::mytesttwo(qobject*parent) :
qobject(parent)
void mytesttwo::setvalue()
if(m_data == 0)
m_data = 1;
else
m_data = 0;
emit valuechange();
int mytesttwo::getvalue()
return m_data;
mytesttwo.h:
#ifndef mytesttwo_h
#define mytesttwo_h
#include
class mytesttwo: public qobject
q_object
public:
explicit mytesttwo(qobject *parent = 0);
q_invokableint getvalue();
signals:
void valuechange();
public slots:
void setvalue();
private:
int m_data;
#endif //mytesttwo_h
jscript.js:
function adjusttest()
console.log("i am jscript")
main.qml:
import qtquick2.3
import qtquick.window2.2
import org.com.mytest1.0
import "jscript.js"as jsfun
//將js檔案引入後可直接呼叫裡面的函式,自定義命名首字母必須大寫,不然後報如下錯誤:invalid import qualifier id
window {
visible: true
width: 360
height: 360
property int flag: 0
rectangle{
id:mybutton
color:"green"
x:100
y:50
width:100
height:50
mousearea{
anchors.fill: parent
onclicked:
jsfun.adjusttest();
flag = mytext.getvalue()
mytext.setvalue();
mytest{
id:mytext
onvaluechange: {
mybutton.color = (flag == 1)?"red":"black"
qml與C 的互動
簡單說下我自己對qml與c 的互動的理解流程 1.介面互動,很多新手可能會寫qt介面或者qml介面,但想要把qml與c 結合起來就一臉矇逼了。首先我提供個簡單的方法實現qml和c 的介面互動,首先引入幾個重要的標頭檔案,當然在專案檔案中需要加qt quickwidgets才能引用以下標頭檔案 inc...
qml與C 的互動
qml與c 的互動,簡單說下我自己對qml與c 的互動的理解流程 1.介面互動,很多新手可能會寫qt介面或者qml介面,但要把qml與c 結合起來就一臉矇逼了。首先我提供個簡單的方法實現qml和c 的介面互動。首先引入幾個重要的標頭檔案 include include include widget ...
棧的兩種C 實現
棧 stack 是限制插入和刪除只能在乙個位置上進行的表,該位置是表的末端,叫做棧的頂 top 它是後進先出 lifo 的。對棧的基本操作只有push 進棧 和pop 出棧 兩種,前者相當於插入,後者相當於刪除最後的元素。棧本質上是一種受限制的表,所以可以使用任何一種表的形式來實現它,最常用的是使用...