Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QStatusBar - replacing widgets from bar



  • Hi,
    I have status bar where I want to have three fields to placing there widgets.
    To have there that fields I can do that:

    @
    QLabel labelOne("");
    QLabel labelTwo("");
    QLabel labelThree("");

    statusBar->insertWidget(0, labelOne, 1); //QStatusBar* statusBar;
    statusBar->insertWidget(1, labelTwo, 1);
    statusBar->insertWidget(2, labelThree, 1);
    @

    I want to have function that replace one of the labels with other widget.
    Is there any possibility to do this without using pointers to that labels.
    I know that I can do this in that way:

    @
    void setWidgetToBar(QWidget* widget, int index)
    {
    switch(index)
    {
    case 0:
    statusBar->removeWidget(labelOne);
    break;
    case 1:
    statusBar->removeWidget(labelTwo);
    break;
    case 2:
    statusBar->removeWidget(labelThree);
    break;
    deafult:
    break;
    }
    ui.statusBar->insertWidget(index, widget, 1);
    }
    @

    But problem is that I don't have only one status bar. Having pointers to all of these labels from all status bars seems to be not good idea. Unless I will create a list of that labels. Is it a good idea or maybe there is any other way to do this?


  • Lifetime Qt Champion

    well, maybe you could
    @
    statusBar->removeWidget(static_cast<QWidget *>(statusBar->children()[0]));
    @
    That is not pretty and would hide any widget at index zero, regardless if it was the label or not.

    I have not testet it. just from looking at the source.


  • Lifetime Qt Champion

    Hi,

    If you have several similar status bars you should rather create a subclass where you handle this. And currently yes, there's not simple way to access a widget from the status bar itself.

    However, never use a static_cast with QObject derived class, use qobject_cast and always verify that the pointer returned is not null.


Log in to reply