How to Bind a QML property to a C++ Function/pt: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 1: Line 1:
[[Category:HowTo]]<br />[[Category:Portuguese::HowTo]]
[[Category:HowTo]]
[[Category:Portuguese::HowTo]]


[[Category:Developing_with_Qt::General]]<br />[[Category:Portuguese::Developing_with_Qt::General]]
[[Category:Developing_with_Qt::General]]
[[Category:Portuguese::Developing_with_Qt::General]]


[[Category:Tutorial]]<br />[[Category:Portuguese::Tutorial]]
[[Category:Tutorial]]
[[Category:Portuguese::Tutorial]]


[toc align_right="yes" depth="2"]
[toc align_right="yes" depth="2"]
Line 10: Line 13:


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":https://bugreports.qt.nokia.com//browse/QTBUG-17323 .
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":https://bugreports.qt.nokia.com//browse/QTBUG-17323 .
<br />Neste artigo, vamos mostrar como viabilizar a associação de propriedades QML e funções usando "Q_PROPERTY":http://doc.qt.nokia.com/latest/qobject.html#Q_PROPERTY juntamente com o sinal "NOTIFY":http://doc.qt.nokia.com/latest/properties.html#qt-s-property-system , que é emitido sempre que o valor da propriedade muda.
 
<br />h2. O Código em C''+
Neste artigo, vamos mostrar como viabilizar a associação de propriedades QML e funções usando "Q_PROPERTY":http://doc.qt.nokia.com/latest/qobject.html#Q_PROPERTY juntamente com o sinal "NOTIFY":http://doc.qt.nokia.com/latest/properties.html#qt-s-property-system , que é emitido sempre que o valor da propriedade muda.
 
h2. 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:
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:
Line 21: Line 26:
Object::someFunction() é chamado a partir do QML pois ele usa "Q_INVOKABLE":http://doc.qt.nokia.com/latest/qobject.html#Q_INVOKABLE. Ela simplesmente muda o status de uma variável membro, e é chamado a cada 5 segundos usando um "QTimer":http://doc.qt.nokia.com/latest/qtimer.html 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.
Object::someFunction() é chamado a partir do QML pois ele usa "Q_INVOKABLE":http://doc.qt.nokia.com/latest/qobject.html#Q_INVOKABLE. Ela simplesmente muda o status de uma variável membro, e é chamado a cada 5 segundos usando um "QTimer":http://doc.qt.nokia.com/latest/qtimer.html 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<br /></code><br />#include <QtGui><br />#include <QtDeclarative>
main.cpp
</code>
#include <QtGui>
#include <QtDeclarative>


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


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


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


}
}


Q_INVOKABLE void someFunction(int i)<br /> {<br /> if ( i  0) {
Q_INVOKABLE void someFunction(int i)
{
if ( i  0) {
   theValue = 0;
   theValue = 0;
   }
   }
   if (i  1) {<br /> theValue = 1;<br /> }
   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;


emit changeOfStatus(i);<br /> }
};


signals:<br /> void changeOfStatus(int i) ;<br /> public slots:<br /> void testSlot()<br /> {<br /> if (changeMe)<br /> {<br /> someFunction(0);<br /> } else {<br /> someFunction(1);<br /> }<br /> changeMe = !changeMe;<br /> }
#include "main.moc"


private:<br /> bool changeMe;<br /> int theValue;<br /> QTimer '''myTimer;
int main(int argc, char'''* argv)
<br />};
{
<br />#include "main.moc"
QApplication app(argc, argv);
<br />int main(int argc, char'''* argv)<br />{<br /> QApplication app(argc, argv);<br /> Object myObj;<br /> QDeclarativeView view;<br /> view.rootContext()->setContextProperty("rootItem", (QObject *)&amp;myObj);<br /> view.setSource(QUrl::fromLocalFile("main.qml"));<br /> view.show();<br /> return app.exec();
Object myObj;
QDeclarativeView view;
view.rootContext()->setContextProperty("rootItem", (QObject *)&amp;myObj);
view.setSource(QUrl::fromLocalFile("main.qml"));
view.show();
return app.exec();


}<br /><code>
}
<code>


== O Código QML ==
== O Código QML ==
Line 57: Line 113:
main.qml
main.qml


</code><br />import QtQuick 1.0
</code>
import QtQuick 1.0


Rectangle {<br /> width: 440; height: 150
Rectangle {
width: 440; height: 150


Column {<br /> anchors.fill: parent; spacing: 20
Column {
anchors.fill: parent; spacing: 20


Text {<br /> text: rootItem.theChange<br /> font.pointSize: 25; anchors.horizontalCenter: parent.horizontalCenter
Text {
text: rootItem.theChange
font.pointSize: 25; anchors.horizontalCenter: parent.horizontalCenter


}<br /> }<br />}<br /><code>
}
}
}
<code>

Revision as of 11:40, 25 February 2015


[toc align_right="yes" depth="2"]

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":https://bugreports.qt.nokia.com//browse/QTBUG-17323 .

Neste artigo, vamos mostrar como viabilizar a associação de propriedades QML e funções usando "Q_PROPERTY":http://doc.qt.nokia.com/latest/qobject.html#Q_PROPERTY juntamente com o sinal "NOTIFY":http://doc.qt.nokia.com/latest/properties.html#qt-s-property-system , que é emitido sempre que o valor da propriedade muda.

h2. 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 "Q_INVOKABLE":http://doc.qt.nokia.com/latest/qobject.html#Q_INVOKABLE. Ela simplesmente muda o status de uma variável membro, e é chamado a cada 5 segundos usando um "QTimer":http://doc.qt.nokia.com/latest/qtimer.html 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 "Rectangle":http://doc.qt.nokia.com/latest/qml-rectangle.html 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

}

}

}