[SOLVED] Dynamically refer to labels

  • Hello
    How can I replace the following line with a dynamic reference:


    so that the label name is passed as a QString? I'm looking for something comparable to the following pseudo:

    @void ns::setText(QString labelName, QString text){

    Is this possible? (One way of course is to add the labels to a QMap<QString, QLabel*> with the same key as the label name, but this is a bit clumsy if there are a lot of labels...)

  • All labels have ObjectName parameter, so you don't need QMap for that.
    Also you can check "QSignalMapper":http://qt-project.org/doc/qt-5.0/qsignalmapper.html

  • I'm sorry, but I don't really understand your reply... I know each label has a object name, and that I can't refer to it directly, but my question was how to do it dynamically? not to have to write statically:


    the Qmap enables me to first push this label to the map

    @labelMap["timeLabel"] = this->ui->timeLabel;@

    and then dynamically use it:

    @void ns::changeLabelText(QString labelName, QString text){

    But is there any way of doing this without the QMap?

  • I don't really understand your problem too. Were the labels are? In the same class? Globally somewhere?
    If they are all in the same class, you can simply qobject_cast<QLabel *>(this) and find out needed label by the object name...

  • All the labels are in the same class, added via the Qt Designer, hence


    I know the name of all the labels, I just want to construct one function that sets a given text to the label which name is passed as a string, my problem is how to "link the string to the correct label"?

    There are about 300 labels in this one class, and the name of the labels are stored externally, that's why I'd like to create a function that is able to refer to the label named the same as what's passed in the name string.


  • Then construct this function using qobject_cast or using QObject function findChild, which uses qobject-cast! Whats the problem? Have you read about qobject_cast already?

    void YourMainWdiget::SetNamedLabelText(const QString & label_name, const QString & text)
    QLabel * lbl = this->findChild<QLabel *>(label_name);

  • Your example was precisely what I need ! Thanks a lot!

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.