I have a Qt application with a simple QLabel. I wondered if it was possible to update automatically its text since the QLabel constructor uses a reference.
QLabel ( const QString & text, QWidget * parent = 0, Qt::WindowFlags f = 0 )
What I'd like to have is a QLabel whose text is updated when I change the QString contents.
I tried the following code (using Qt 5.0.2) :
#include <QtGui>
#include <QtWidgets>
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str("test");
QLabel label(str);
label.setFixedSize(300,70);
label.show();
str = "yoh";
label.repaint();
return app.exec();
}
But the label still shows « test ». So, am I doing something wrong, or is it just not possible to update automatically the content ?
Any help would be appreciated. By the way, there is no problem if I have to subclass QLabel.
Actually you can do it. You need to create model.
QLabel label;
label.show();
QStandardItemModel *model = new QStandardItemModel(1,1);
QStandardItem *item1 = new QStandardItem(QStringLiteral("test"));
model->setItem(0, 0, item1);
Add a mapping between a QLabel and a section from the model, by using QDataWidgetMapper.
QDataWidgetMapper *mapper = new QDataWidgetMapper();
mapper->setModel(model);
mapper->addMapping(&label,0,"text");
mapper->toFirst();
Every time the model changes, QLabel is updated with data from the model.
model->setData(model->index(0,0),"yoh");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With