Search code examples
c++qtqt5qtoolbutton

How to properly manage text and icon with QToolButton?


I have code snippet looks like this:

nextPageBtn = new QToolButton();
nextPageBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
nextPageBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
nextPageBtn->setIcon(QIcon(":/next.png"));
nextPageBtn->setText("Next");

Currently I have two problems with this.

First:
I want the text is on the left of the icon, but with the code I provide, the text is on the right like this: enter image description here

Second:
When the window is enlarged, I can not figure out a way to keep the text and icon in the center of the button. It looks like this when the button gets bigger:enter image description here

Edit:
This is how I manage the layout:

nextPageHLayout = new QHBoxLayout; //This is the layout for QToolButton, it has two spacers and a QToolButton
mainVLayout->addLayout(nextPageHLayout); //mainVLayout is the main layout, and I put the mainVLayout to the central widget, and it also contains a QLabel above the nextPageHLayout

QSpacerItem *leftBtnSpacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed);
nextPageHLayout->addSpacerItem(leftBtnSpacer);

nextPageBtn = new QToolButton(mainWidget);
nextPageHLayout->addWidget(nextPageBtn);
nextPageBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
nextPageBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
nextPageBtn->setIcon(QIcon(":/next.png"));
nextPageBtn->setText("Next");

QSpacerItem *rightBtnSpacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed);
nextPageHLayout->addSpacerItem(rightBtnSpacer);

Solution

  • You must make the following changes:

    • You should not change the size policy of the QToolButton, that's why it's expanding.

    • You must change the layoutDirection to Qt::RightToLeft.


    QHBoxLayout * nextPageHLayout = new QHBoxLayout; //This is the layout for QToolButton, it has two spacers and a QToolButton
    mainVLayout->addLayout(nextPageHLayout); //mainVLayout is the main layout, and it also contains a QLabel above the nextPageHLayout
    
    QSpacerItem *leftBtnSpacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum);
    nextPageHLayout->addSpacerItem(leftBtnSpacer);
    
    nextPageBtn = new QToolButton(mainWidget);
    nextPageHLayout->addWidget(nextPageBtn);
    nextPageBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    nextPageBtn->setIcon(QIcon(":/next.png"));
    nextPageBtn->setText("Next");
    nextPageBtn->setLayoutDirection(Qt::RightToLeft);
    
    QSpacerItem *rightBtnSpacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum);
    nextPageHLayout->addSpacerItem(rightBtnSpacer);
    

    enter image description here

    enter image description here