Search code examples
c++qtstatusbar

QObject::findChild returns 0 for QLabels added to statusbar


I created a application running in a QMainWindow using qtcreator, so the typical way.

I added two 'manually' (meaning: not with the Form editor) created qlabels to the statusbar:

in the header:

QLabel *label_timestamp;
QLabel *contentLabel_timestamp;

in the constructor:

MainWin::MainWin(const CmdLineOptions &opts, QWidget *parent)
: QMainWindow(parent),
  ui(new Ui::MainWin),
  m_connectionStatusLabel(new QLabel),
  m_client(new QMqttClient),
  m_mqttmanager(new MQTTManager(m_client)),
  m_mqttServerName("localhost")
{
    ui->setupUi(this);

    label_timestamp = new QLabel(this);
    contentLabel_timestamp = new QLabel(this);

    label_timestamp->setText("system time");
    contentLabel_timestamp->setText("dd.mm.yyyy, hh:mm:ss:zzz"); /* just testing output */

    statusBar()->addPermanentWidget(label_timestamp);
    statusBar()->addPermanentWidget(contentLabel_timestamp);
}

If I do a

Label *label = findChild<QLabel *>(QString("contentLabel_")+objName);

elsewhere in this class implementation with objName being 'timestamp', of course, findChild() returns 0. It's working fine with other QLabels created using QtCreator in the form editor, findChild() finds them all. Isn't the statusbar widget and its content also a child of ui? Does somebody eventually know a way out of there?

I want to use findChild to generically fill my labels following a naming scheme with content I receive over MQTT, this is the background. Would be great if the statusbar content would need a special handling but could also be handled in this dynamic approach.

Thanks a lot


Solution

  • findChild uses the objectName, in the case of Qt Creator this establishes it in the MOC, but in your case you must establish it:

    label_timestamp = new QLabel(this);
    contentLabel_timestamp->setObjectName("label_timestamp");
    contentLabel_timestamp = new QLabel(this);
    contentLabel_timestamp->setObjectName("contentLabel_timestamp");
    

    And then you can recover it with:

    QLabel *label_1 = findChild<QLabel *>("label_timestamp");
    if(label_1){
        // some code
    }
    QLabel *label_2 = findChild<QLabel *>("contentLabel_timestamp");
    if(label_2){
        // some code
    }