QT中C++与QML实现交互的两种基本方式
(1)注册上下文(将C++对象嵌入到带有上下文属性的QML中)
main.cpp:
#include<QGuiApplication>
#include<QQuickView>
#include<QQmlContext>
#include"mytest.h" //包含三个基本的库文件以及类的头文件
int main(intargc, char *argv[])
{
QGuiApplication app(argc, argv);
MyTest data; //定义一个类对象
QQuickView view;
view.rootContext()->setContextProperty("myObjectExposeByCXProperty",&data);
view.setSource(QUrl("qrc:/main.qml"));
view.show();
return app.exec();
}
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<QObject>
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<QGuiApplication>
#include<QQmlApplicationEngine>
#include<QtQml>
#include"mytesttwo.h"
int main(intargc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<MyTestTwo>("org.com.mytest",1,0,"MyTest");
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
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<QObject>
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"
}
}
}