Hi I'm pretty new in Qt.
Can I binding class attribute(or property) to QLabel text? For example,
class Dog{
string name;
}
QLabel lbl;
When I change dog's name, I'd like to change lbl.text
In Qt things that you are talking about - territory of signals and slots good way to do:
Dog.h
#ifndef DOG_H
#define DOG_H
#include "QObject"
class Dog: public QObject
{
Q_OBJECT
public:
void setDogsName(const QString &name)
{
m_Name = name;
emit dogsNameChanged(name);
}
signals:
void dogsNameChanged(const QString &name);
private:
QString m_Name;
};
#endif // DOG_H
Q_OBJECT macro need for signals/slots connections works (and its got to be in private section/above public:). Code got to be in separated.h file ( )
main:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QLabel lbl;
Dog dog;
QObject::connect(&dog, &Dog::dogsNameChanged, &lbl, &QLabel::setText);
dog.setDogsName("TEST");
lbl.show();
return a.exec();
}
result: here
read about connections in Qt https://doc.qt.io/qt-6/signalsandslots.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.