How to bind C++ property to QML property?

浪尽此生 提交于 2020-05-12 20:03:23

问题


So I know how to bind QML property to C++ property, so when C++ one calls notify signal, QML updates the view. Is there any way to make C++ property update when user changes something using UI?

For example, I have a Combobox, and I want some C++ property to be updated when user changes value of combobox.

EDIT: By C++ properties I mean Q_PROPERTY macro in QObject-derived classes.


回答1:


To bind a property from an object you didn't create in QML (or was created in another context), you have to use Binding. In your case :

Binding {
    target: yourCppObject
    property: "cppPropertyName"
    value: yourComboBox.currentText
}



回答2:


Perhaps an answer to a similar question would be helpful.

It shows how to connect the standard (not custom) qml property with something in C++.




回答3:


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.

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



来源:https://stackoverflow.com/questions/41591224/how-to-bind-c-property-to-qml-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!