tags:

views:

290

answers:

3

I'm trying to build programmaticaly (with Qt 4.6) a window containing a series of QPushButton's, all packed together. It should look like so (which I call a toolbox):

toolbox image

So, I created a Toolbox class, deriving from QWidget, that has the following constructor:

Toolbox::Toolbox (void)
  : QWidget (0, Qt::Tool)
{
  setWindowTitle (tr ("Toolbox"));

  QGridLayout *group = new QGridLayout (this);
  group->setSpacing (0);
  group->setContentsMargins (0, 0, 0, 0);
  group->setSizeConstraint (QLayout::SetFixedSize);
  setLayout (group);

  unsigned k = 0;
  QPushButton *buttons = new QPushButton[6];
  for (unsigned i = 0; i < 3; i++)
    for (unsigned j = 0; j < 2; j++)
    {
      buttons[k].setIcon (QIcon ("test.png"));
      buttons[k].setIconSize (QSize (32, 32));
      buttons[k].setContentsMargins (0, 0, 0, 0);
      buttons[k].setCheckable (true);
      buttons[k].setAutoExclusive (true);

      group->addWidget (&buttons[k], i, j);
      k++;
    }
  buttons[1].setChecked (true);

Somehow, it does not work and my buttons don't end up packed together:

result

I can't manage to remove this vertical spacing (and the margins surrounding the entire array). Any help is welcome.

A: 

Since you've set the size constraint on the layout to QLayout::SetFixedSize, Qt will use the size hint of the widget as its fixed size. You might have to override QWidget::sizeHint() in the Toolbox class to make the widget exactly as large as it needs to be to fit all the buttons (in the case of your six buttons, the width would be 64 and the height would be 96).

RA
Hum, I'm afraid it does not come into play. I added a Toolbox::sizeHint(), but it does not get called.
FX
Toolbox::sizeHint() gets called when I try it. It doesn't get called when I forget to make it a const member function. You'll probably also have to change the style as PiedPiper suggests.
RA
OK, right, another case of editing and compiling different files, sorry. (I got the `const` right, though.)However, even when called, it can make it return whatever QSize I want, and I doesn't change the appearance at all.Finally, regarding setting the style, if I do that then no other trick is needed (but it's ugly).
FX
A: 

If you are using the the plastique style which is now standard in Qt4.6 the borders of QPushButtons are drawn inside the widget. Try using one of the other styles. e.g.:

#include <QGtkStyle>

QApplication a(argc, argv, true);
a.setStyle("gtk");

A style can also be set on an individual widget using the QWidget::setStyle() function.

PiedPiper
I'm working on Mac OS, so I'm not using plastique. Actually, setting the style to plastique makes it draw widgets packed together. However, this gives them an alien look, so I'd still welcome a solution with the native type.
FX
+5  A: 

Apparently, this is considered a normal thing: see the corresponding bug report, which was closed. The workaround reported there doesn't seem to work for me.

FX