Right aligning a button in a QToolBar
Sometimes you will want to add a right-aligned button to a QToolBar
. The first thing that probably comes to mind is to add a QSpacerItem
to the toolbar, but that won't work as QSpacerItem
is not a child of QWidget
, so you can't use the addWidget()
member of QToolBar
. Instead, make a basic QWidget
, set its sizePolicy
to Expanding
, and add that widget to your QToolBar
. For example:
QWidget* spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // toolBar is a pointer to an existing toolbar toolBar->addWidget(spacer); toolBar->addAction("Right-aligned button");
If you end up using a lot of these spacers you could even create a subclass.