Right aligning a button in a QToolBar

—richardwb on Thursday, April 23, 2009 @ 08:32

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.

Comments

  1. Simon Greenwold
    Saturday, August 8, 2009 @ 12:48

    Thanks!

  2. Ulf
    Thursday, December 3, 2009 @ 06:25

    Thanks, just what I needed! Was desperately looking for QToolbar::addSpacer() ;)

  3. ken ampel
    Friday, February 12, 2010 @ 14:54

    Works perfectly! Simple! Thanks very much!!!

Add a comment
(?)

BBCode