C++和QML混合编程(下):C++中调用QML

C++中调用QML,主要通过调用QML对象成员,方法以及与QML信号关联:

1.C++中使用QML对象成员

Item{
property int someValue: 200
}
为了能够在C++中访问QML定义的成员变量someValue,可以使用QQmlProperty的read()和write()、QObject::setProperty()和QObject::Property()

在main.cpp中
QQmlApplicationEngine engine;
QObject *object=engine.rootObjects().at(0);
qDebug()<<"Property value:"<<QQmlProperty::read(object,"someValue").toInt();
QQmlProperty::write(object,"someValue",5000);
 qDebug()<<"Property value 2:"<<object->property("someValue").toInt();
 object->setProperty("someValue",100);
 qDebug()<<"Property value 3:"<<object->property("someValue").toInt();
 qDebug()<<"Property width value:"<<object->property("width").toInt();

2.C++中调用QML方法

利用C++的函数QMetaObject::invokeMothod()可以调用所有QML的方法。QML提供的方法的参数和返回值通常传递为 C++提供的QVariant类型值。

QML中定 function myQmlFunction(msg)
{
console.log(“Got message 1:”,msg)
return “some retrun value 1”
}
main.cpp中调用:
QVariant returnedValue;
QVariant msg1=”Hello from C++”;
//C++ 调用QML 方法
QMetaObject::invokeMethod(object,”myQmlFunction”,Q_RETURN_ARG(QVariant,returnedValue),Q_ARG(QVariant,msg1));
qDebug()<<”QML Function returned:”
<< returnedValue.toString();.

3.与QML信号关联

QML中所有的信号都可以与C++的槽函数关联。为了能够与QML信号关联,在C++中均使用QObject类提供connecQML中定义信号:
signal qmlSignal(string qmlMsg)
Button{
id:m_button2
anchors.bottom: parent.bottom
anchors.bottomMargin: 100
text:qsTr(“发送QML信号”)
onClicked: root.qmlSignal(“Hello Signal from QML”); //发送QML信号到C++
}
C++中定义槽函数:
Message类中
public slots:
void qmlToCppSlot(QString );
void Message::qmlToCppSlot(QString str)
{
qDebug()<< tr(“我从QML界面获取了信号”)<< str;
}
main.cpp中连接对应信号槽:
QObject *object=engine.rootObjects().at(0);
QObject::connect(object,SIGNAL(qmlSignal(QString )),&msg,SLOT(qmlToCppSlot(QString ))); //连接QML信号到C++槽

4.定时改变QML主界面背景颜色

定义ChangeQmlColor类,用定时器去定时更新QML界面

 ChangeQmlColor::ChangeQmlColor(QObject *target, QObject *parent)
    : QObject(parent)
    , m_timer(this)
    , m_target(target)
{
    qsrand(QDateTime::currentDateTime().toTime_t());
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
    m_timer.start(1000);
}
 QColor color = QColor::fromRgb(qrand()%256, qrand()%256, qrand()%256);//QML主界面颜色改变
    m_target->parent()->setProperty("color", color);
    在main.cpp中:
    QObject *object=engine.rootObjects().at(0);
        QObject * quitButton =object->findChild<QObject*>("quitButton");
         new ChangeQmlColor(quitButton);

在QML中 objectName: “quitButton”的按钮的父类就是顶层root,因此C++中m_target->parent()->setProperty(“color”, color);实际上就是设置了window的背景色

转载请注明出处:https://blog.csdn.net/qq_35173114/article/details/80873377
源码链接:https://download.csdn.net/download/qq_35173114/10511661

猜你喜欢

转载自blog.csdn.net/qq_35173114/article/details/80873377