Important: Please read the Qt Code of Conduct -

[SOLVED]how can i add a toolbar for a QWidget not QMainWindow?

  • how can i add a toolbar for a QWidget not QMainWindow?
    i want to add toolbar on a QDockWidget(not a QMainWindow),
    i just create QToolBar("xxx", pDockWidget);and this is not enought, what should i do then to make it apear right as the toolbar on QMainWindow.

    another question is : is it only One QMainWindow for an app ,right? if i can use many QMainWindow here, i can setCentralWidget(pAnothereMainWindow) here.

    thank you

  • Moderators

    Hi and welcome

    To easily place the toolbar in your widget use its layout manager, e.g.:

    auto tb = new QToolBar();
    auto dockLayout = new QVBoxLayout(); //or any other layout type you want
    dockLayout->setMenuBar(tb); // <-- the interesting part
    auto dockContent = new QWidget();

    As for the second question: you can have as many QMainWindows as you want. They are nothing more than a specialized QWidget, just like any other.
    You can nest them as you wish too.

  • thank you very much.
    i just tried
    dockLayout->addWidget(tb); //also works
    ur solution: dockLayout->setMenuBar(tb); // also work

    may i ask: what is the differnece?

  • Moderators

    The difference is that setMenuBar places the widget outside of the layout content, so the top margin of the layout is below the bar . With addWidget the bar is added as a layout content, so it respects the margins (controlled by setContentsMargins).
    For menus and toolbars we usually want them to stick to edges without a gap, so the setMenuBar method is more appropriate for it.

  • but i fount setMenuBar makes the gap distance between the toolbar and the widget below it, large gap.
    how can i make this gap distance smaller, can i set the value?

  • Moderators

    This is the gap created by the usual layout margin. If you don't want it reduce the top margin of the layout using setContentsMargin of the layout with the top argument set to whatever you want.

  • already tried to set all setContentsMargin of QToolbar, and the Widget below it , and the layout.
    It seems that it has to have some edge distance between the toolbar and the widget, even when i set all the margins to 0.

  • Moderators

    I just tried this:

    auto toolbar = new QToolBar();
    toolbar->setStyleSheet("QToolBar {border: 1px solid blue }");
    auto someWidget = new QWidget();
    someWidget->setStyleSheet("border: 1px solid red");
    auto layout = new QVBoxLayout();
    auto dockContent = new QWidget();

    This results in this layout:
    Toolbar image
    I see no gap between the toolbar and the widget.

  • ok,thank you

Log in to reply