2017-01-11 103 views
3

所以我知道如何将QML属性绑定到C++属性,所以当C++调用通知信号时,QML更新视图。当用户使用UI改变某些东西时,有什么办法可以使C++属性更新?如何将C++属性绑定到QML属性?

例如,我有一个组合框,并且我希望在用户更改组合框的值时更新一些C++属性。

编辑:由C++属性我的意思是Q_PROPERTY宏在QObject衍生类。

回答

2

要绑定的对象,你没有在QML创建一个属性(或者在另一种情况下被创造),你必须使用Binding。 你的情况:

Binding { 
    target: yourCppObject 
    property: "cppPropertyName" 
    value: yourComboBox.currentText 
} 
-1
1) Firstly you have to create main.cpp page. 

#include <QtGui> 
#include <QtDeclarative> 

class Object : public QObject 
{ 
Q_OBJECT 
Q_PROPERTY(QString theChange READ getTheChange NOTIFY changeOfStatus) 

public: 
    Object() { 
    changeMe = false; 
    myTimer = new QTimer(this); 
    myTimer->start(5000); 
    connect(myTimer, SIGNAL (timeout()), this, SLOT (testSlot())); 
    } 

    QString getTheChange() { 
    if (theValue 0) { 
    return "The text changed"; 
    } if (theValue 1) { 
    return "New text change"; 
    } 
    return "nothing has happened yet"; 
    } 

    Q_INVOKABLE void someFunction(int i) { 
    if (i 0) { 
    theValue = 0; 
    } 
    if (i 1) { 
    theValue = 1; 
    } 
    emit changeOfStatus(i); 
    } 

    signals: 
    void changeOfStatus(int i) ; 

    public slots: 
    void testSlot() { 
    if (changeMe) { 
    someFunction(0); 
    } else { 
    someFunction(1); 
    } 
    changeMe = !changeMe; 
    } 

    private: 
    bool changeMe; 
    int theValue; 
    QTimer *myTimer; 
}; 

#include "main.moc" 

int main(int argc, char* argv[]) 
{ 
QApplication app(argc, argv); 
Object myObj; 
QDeclarativeView view; 
view.rootContext()->setContextProperty("rootItem", (QObject *)&myObj); 
view.setSource(QUrl::fromLocalFile("main.qml")); 
view.show(); 
return app.exec(); 
} 

2) The QML Implementation main.qml 
In the QML code below we create a Rectangle that reacts to mouse clicks. The text is set to the result of the Object::theChange() function. 

import QtQuick 1.0 

Rectangle { 
width: 440; height: 150 

Column { 
    anchors.fill: parent; spacing: 20 
    Text { 
    text: rootItem.theChange 
    font.pointSize: 25; anchors.horizontalCenter: parent.horizontalCenter 
    } 
} 
} 

So, using the approach in the example above, we get away for QML properties to react to changes that happen internally in the C++ code. 

来源:https://wiki.qt.io/How_to_Bind_a_QML_Property_to_a_C%2B%2B_Function

+5

这是一个低质量的答案是:不要一味的复制粘贴其他网站甚至没有引用来源,并仔细阅读的问题。 –

相关问题