Calling a variable from C++ in QML
-
I have a header file, and i defined the class, the signals as follows:
Mysystem.hclass Mysystem : public SystemCan { Q_OBJECT Q_PROPERTY(QString pNumber MEMBER m_pNumber NOTIFY pNumberChanged) public: explicit Mysystem(quint8 x, quint64 y, QObject *parent = 0); signals: void pNumberChanged(); private: QString m_pNumber; };
and functions are set in .h file and .cpp file as well.
When I tried to get the value of pNumber I did this also in my main c++ file:
main.cpp
Mysystem mysystem; // but here i got an error because i should give 2 arguments, but i dont know how to do this viewer.rootContext()->setContextProperty("thepnumber", &mysystem);
In my QML file i just want to read this variable like this:
console.log (thepnumber.pNumber)
I wonder how to solve this argument problem, or if there is another way to solve this, i would appreciate that
-
@mamoud said in Calling a variable from C++ in QML:
Q_PROPERTY(QString pNumber MEMBER m_pNumber NOTIFY pNumberChanged)
This will not do what you think it will do.
Q_PROPERTY
doesn't do any magic on the NOTIFY argument, it will not get automatically triggered if you set the property, you should split it into READ and WRITE and implement emitting the signal in the WRITE method@mamoud said in Calling a variable from C++ in QML:
but here i got an error because i should give 2 arguments, but i dont know how to do this
Just pass them to the constructor:
Mysystem mysystem(0,0);
-
-
thanks
do you mean like this:Q_PROPERTY(QString pNumber READ pNumber_read WRITE pNumber_write NOTIFY pNumber_changed)
and adding this as well:
public: QVariant pNumber_read() const; public slots: void pNumber_write(QString value); // i am not sure about this signals: void pNumber_changed(); private: QString m_pNumber;
-
Q_PROPERTY(QString pNumber READ pNumber WRITE setPNumber NOTIFY pNumberChanged)
public: const QString& pNumber() const {return m_pNumber;} void setPNumber(const QString& val){ if(val==m_pNumber) return; m_pNumber=val; pNumberChanged(m_pNumber); } signals: void pNumberChanged(const QString& pN); private: QString m_pNumber;
-
Pro (QtCreator) tip:
write
Q_PROPERTY(QString pNumber READ pNumber WRITE setPNumber NOTIFY pNumberChanged)
right click on
Q_PROPERTY
selectRefactor
click onGenerate Missing Q_Property Members
saves a lot of time
-
@mamoud said in Calling a variable from C++ in QML:
Great thank you,
but i still have this problem, that i cannot read the value in QML when i write this:
console.log (thepnumber.pNumber)
it shows nothing
more context please, where exactly is this called?
//General solution
Connections{
target: thepnumberonpNumberChanged: console.log(thepnumber.pNumber)
} -