How to Bind a QML property to a C++ Function/pt

From Qt Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

Associando uma propriedade QML a uma função em C++

No momento o QtQuick não suporta um modo de ligar uma propriedade QML ao resultado de uma função em C+. No entanto, existe uma sugestão para adicionar suporte a este recurso aqui .

Neste artigo, vamos mostrar como viabilizar a associação de propriedades QML e funções usando Q_PROPERTY juntamente com o sinal NOTIFY , que é emitido sempre que o valor da propriedade muda.

O Código em C+

Na classe Object no exemplo abaixo, nós criamos uma Q_PROPERTY que é usada para modificar e atualizar o texto do código QML e que tem um sinal changeOfStatus() que é emitido sempre que o status da função em C++ chamada function someFunction() mudar:

Q_PROPERTY(QString theChange READ getTheChange NOTIFY changeOfStatus)<code>

A função Object::getTheChange() modifica o texto de um item QML dependendo do resultado de Object::someFunction(). O resultado é usado como valor do texto da propriedade no código QML.

Object::someFunction() é chamado a partir do QML pois ele usa [http://doc.qt.nokia.com/latest/qobject.html#Q_INVOKABLE Q_INVOKABLE]. Ela simplesmente muda o status de uma variável membro, e é chamado a cada 5 segundos usando um [http://doc.qt.nokia.com/latest/qtimer.html QTimer] para ilustrar como a propriedade QML é capaz de reagir à mudança dessa. Ela pode também ser chamada a partir do código QML ao clicar no texto. Por fim, ela emite o sinal changeOfStatus() que aciona Object::getTheChange(), que deve ser chamado quando o texto deve ser reavaliado.

main.cpp
  1. include <QtGui>
  2. 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;

};

  1. 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();

}

== O Código QML ==

No código QML abaixo, nós criamos um [http://doc.qt.nokia.com/latest/qml-rectangle.html Rectangle] que reage aos cliques do mouse. O texto é modificado através do resultado da função Object::theChange().

main.qml

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

}

}

}