Search code examples
qtqt-designer

How to add text onto QToolbar with Qt Designer?


I would like to ask, if it is possible to add some text onto QToolBar with Qt Designer?


Solution

  • You could do it in Qt Designer, but it'd be a bad hack an unnecessary. Instead, do it via code. There are two ways:

    1. QToolBar is a widget that graphically represents actions, represented by QAction. You can add an action that is pure text, using the QToolBar::addAction(const QString &). E.g. if the toolbar object is simply called toolbar, you'd write toolbar->addAction("Some text");. This will create a button with given text, and return the corresponding action. Actions are an abstraction: they are devoid of a graphical representation, and they can be a part of multiple widgets (e.g. menus and toolbars). It's the individual widgets that give the actions some "physical shape", e.g. construct a button for each action.

    2. QToolBar, at a lower level, is a collection of widgets, that you can add using QToolBar::addWidget(QWidget *). So, if you want to add some static text, you'd create a label with that text and add it to the toolbar. The action thus created may not seem very useful, since you won't be reacting to the user clicking the text (see p.1 above if you do). But it could be used to show and hide the text if desired, and acts as a handle for the text, allowing you to change the text as well. It is really a QWidgetAction derived class. See below for some code to get you started.

    // The text can be empty, in case it was meant to be set sometime later
    QAction *addText(QToolBar *toolbar, const QString &text = {})
    {
      auto *const label = new QLabel;
      auto *const action = toolbar->addWidget(label);
      // Any changes to the action's text should be propagated to the label.
      QObject::connect(action, &QAction::changed, label, [action,label]{
        label->setText(action->text());
      });
    
      action->setParent(toolbar); // so that the action won't leak
      action->setText(text);
      action->setVisible(true);
      return action;
    }
    
    // inside some method
    auto *action = addText(toolbar, "Some text");
    // sometime later
    action->setText("Some other text");
    

    A more flexible way of doing this would be to derive QWidgetAction to create e.g. StaticTextAction, and put the label creation code into StaticTextAction::createWidget(). But such flexibility is most likely unnecessary, since all you're after here is some static text that applies to the toolbar and has no other use (e.g. you wouldn't add it to any other widgets or menus).