Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create QToolBar in QWidget?

Tags:

c++

qt

qtoolbar

I am trying to add a QToolBar in a QWidget. But I want its functionality to work as if it was a QMainWindow.

Apparently I can not create QToolBar in a QWidget, and using setAllowedAreas does not work with QWidget : it only works with QMainWindow. Also, my QWidget is in a QMainWindow.

How can I create a QToolBar for my widget?

like image 906
njporwal Avatar asked Dec 24 '22 03:12

njporwal


1 Answers

The allowedAreas property only works when the toolbar is the child of a QMainWindow. You can add the toolbar to a layout, but it won't be movable by the user. You can still relocate it programmatically, however.

To add it to a layout for a fictional class inheriting QWidget:

void SomeWidget::setupWidgetUi()
{
    toolLayout = new QBoxLayout(QBoxLayout::TopToBottom, this);
    //set margins to zero so the toolbar touches the widget's edges
    toolLayout->setContentsMargins(0, 0, 0, 0);

    toolbar = new QToolBar;
    toolLayout->addWidget(toolbar);

    //use a different layout for the contents so it has normal margins
    contentsLayout = new ...
    toolLayout->addLayout(contentsLayout);

    //more initialization here
 }

Changing the toolbar's orientation requires the additional step of calling setDirection on the toolbarLayout, e.g.:

toolbar->setOrientation(Qt::Vertical);
toolbarLayout->setDirection(QBoxLayout::LeftToRight);
//the toolbar is now on the left side of the widget, oriented vertically
like image 52
jonspaceharper Avatar answered Dec 28 '22 07:12

jonspaceharper