简体   繁体   中英

Automatically update QLabel text

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");

You can't do that. QtCore library does not provide binding expressions in C++ code but qt does it in QtQml library specially to simplify ui designing. If you are talking about references - you are doing it wrong, and more or less, it is not possible. To update automatically your code should implement a subscriber or observer software design pattern and your QLabel must use it. C++ does not that simple as you might think when you was talking about references.

If you really need a auto-updatable GUI, try QML .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM