Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically update QLabel text

Tags:

c++

qt

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.

like image 682
lephe Avatar asked Jan 10 '23 01:01

lephe


1 Answers

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");
like image 116
Meefte Avatar answered Jan 14 '23 19:01

Meefte