2017-01-11 24 views
3

QMLプロパティをC++プロパティにバインドする方法を知っているので、C++が通知信号を呼び出すと、QMLによってビューが更新されます。ユーザーがUIを使って何かを変更したときにC++プロパティの更新を行う方法はありますか?QMLプロパティにC++プロパティをバインドする方法は?

たとえば、私はComboboxを持っており、ユーザーがコンボボックスの値を変更したときに更新されるC++プロパティが必要です。

EDIT: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

これは、低品質の答えです。 –

関連する問題