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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With