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!!!

  4. mistik1
    Friday, January 21, 2011 @ 11:11

    This is a great idea, however it seems that it breaks down if you happen to put another toolbar on the right of the push one. It completely ignores the spacer widget

  5. richardwb
    Monday, January 24, 2011 @ 00:05

    The QToolBar layout engine is very aggressive about having the rightmost (in left-to-right languages) toolbar fill all the remaining space it can. The reason why the spacer just disappears is its minimum width is 0.

    One way I can see to do this would be to update the minimum size for the spacer (via setMinimumWidth or overriding minimumSizeHint) so that it takes up all the remaining space, minus the size of the QToolBars on the right. The code will probably be pretty ugly...

  6. Ramiz
    Monday, February 21, 2011 @ 01:41

    Much appreciated. :)

  7. developer
    Thursday, April 7, 2011 @ 02:42

    Thaaaannnnnnnks!!!!!!!!!!!

  8. jingwei
    Tuesday, August 30, 2011 @ 05:50

    THX!!!!

  9. blueliuyun
    Wednesday, November 23, 2011 @ 04:02

    Thanks!

Add a comment
(?)

BBCode