如何使用QToolButton正确管理文本和图标?

时间:2018-04-14 05:42:11

标签: c++ qt qt5 qtoolbutton

我的代码片段如下所示:

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

目前我有两个问题。

第一:
我希望文本位于图标的左侧,但是使用我提供的代码,文本在右边,如下所示: enter image description here

第二
当窗口放大时,我无法找到将文本和图标保持在按钮中心的方法。当按钮变大时,它看起来像这样:enter image description here

修改:
这就是我管理布局的方式:

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);

1 个答案:

答案 0 :(得分:2)

您必须进行以下更改:

  • 您不应更改QToolButton的尺寸政策,这就是它扩展的原因。

  • 您必须将layoutDirection更改为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

相关问题