2017-01-11 10 views
3

QML 속성을 C++ 속성에 바인딩하는 방법을 알고 있으므로 C++에서 신호 알림을 호출하면 QML에서보기를 업데이트합니다. 사용자가 UI를 사용하여 뭔가를 바꿀 때 C++ 속성 업데이트를 할 수있는 방법이 있습니까?QML 속성에 C++ 속성을 바인딩하는 방법은 무엇입니까?

예를 들어, 나는 콤보 박스를 가지고 있으며 사용자가 콤보 박스의 값을 변경할 때 일부 C++ 속성을 업데이트하려고합니다.

편집 : C++ 속성에 의해 나는 매크로에서 QObject - 유래 클래스를 의미합니다.

답변

2

, 당신은 Binding를 사용할 필요는 QML에서 작성하지 않은 객체의 속성을 바인딩 (또는 다른 컨텍스트에서 만든). 귀하의 경우에는 :

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

이 낮은 품질의 대답은 : 맹목적으로도 소스를 인용하지 않고 다른 웹 사이트를 복사 - 붙여 넣기, 조심스럽게 질문을 읽지 않는다. –

관련 문제