QToolButton visual behavior inside a QFrame/QWidget

1.1k Views Asked by At

I have realised that a QToolButton works differently when added to a QToolBar compared to how it behaves when added to a layout of a QFrame/QWidget.

What style option do I need to set on the QToolButton, so it behaves inside a QFrame exactly the same way as it would (visually) inside a QToolBar?

My current platform is OS X, this behavioral difference is same on both Qt 4.8 and 5.1 (upon my tests).

Thank you

Example:

QToolButton behavior difference

Code used to create the below scenario:

int main(int argc, char **argv)
{
  QApplication app(argc,argv);

  QMainWindow* window    = new QMainWindow();
  QWidget* centralWidget = new QWidget();
  QVBoxLayout* layout    = new QVBoxLayout();

  centralWidget->setLayout(layout);
  window->setCentralWidget(centralWidget);
  window->setWindowTitle("QToolButton inside QToolBar vs QFrame/QWidget");

  layout->setContentsMargins(0, 0, 0, 0);
  layout->setSpacing(30);

  QToolBar* toolBar = new QToolBar();
  toolBar->setOrientation(Qt::Horizontal);
  layout->addWidget(toolBar);

  QToolButton* button_1 = new QToolButton();
  button_1->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
  button_1->setIcon(QPixmap(":/icons/icons/1.png"));
  button_1->setIconSize(QSize(32, 32));
  button_1->setText("Button 1");
  toolBar->addWidget(button_1);

  QToolButton* button_2 = new QToolButton();
  button_2->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
  button_2->setIcon(QPixmap(":/icons/icons/2.png"));
  button_2->setIconSize(QSize(32, 32));
  button_2->setText("Button 2");
  toolBar->addWidget(button_2);

  QToolButton* button_3 = new QToolButton();
  button_3->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
  button_3->setIcon(QPixmap(":/icons/icons/3.png"));
  button_3->setIconSize(QSize(32, 32));
  button_3->setText("Button 3");
  // toolBar->addWidget(button_3);

  QToolButton* button_4 = new QToolButton();
  button_4->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
  button_4->setIcon(QPixmap(":/icons/icons/4.png"));
  button_4->setIconSize(QSize(32, 32));
  button_4->setText("Button 4");
  // toolBar->addWidget(button_4);

  QFrame* frame     = new QFrame();
  frame->setStyleSheet("QFrame { background: #ff0; }");
  layout->addWidget(frame);

  QHBoxLayout* frame_layout = new QHBoxLayout();
  frame_layout->setContentsMargins(0, 0, 0, 0);
  frame_layout->setSpacing(0);
  frame->setLayout(frame_layout);

  frame_layout->addWidget(button_4);
  frame_layout->addWidget(button_3);
  // button_4->animateClick(10000);
  frame_layout->addStretch();

  window->show();
  return app.exec();
}
1

There are 1 best solutions below

3
On

What you see is desired behavior and is coherent with visual behavior of other OS X applications, as far as I can tell. You may want to rethink whether what you're after is advisable. If you come up with a good reason, then I can look further into it.