C++ 如何使用QToolButton正确管理文本和图标?
我的代码片段如下所示:C++ 如何使用QToolButton正确管理文本和图标?,c++,qt,qt5,qtoolbutton,C++,Qt,Qt5,Qtoolbutton,我的代码片段如下所示: nextPageBtn = new QToolButton(); nextPageBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); nextPageBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); nextPageBtn->setIcon(QIcon(":/next.png")); nextPageBtn->se
nextPageBtn = new QToolButton();
nextPageBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
nextPageBtn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
nextPageBtn->setIcon(QIcon(":/next.png"));
nextPageBtn->setText("Next");
目前我对此有两个问题。
第一:
我希望文本位于图标的左侧,但根据我提供的代码,文本位于右侧,如下所示:
第二:
当窗口被放大时,我想不出一种方法来将文本和图标保持在按钮的中心。当按钮变大时,看起来是这样的:
编辑:
这是我管理布局的方式:
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);
您必须进行以下更改: 您不应该更改QToolButton的大小策略,这就是它正在扩展的原因 必须将更改为Qt::RightToLeft
您是将QToolButton直接放置到QToolBar还是放置在何处?@eyllanesc我将“QToolButton”放置在“QHBoxLayout”上,并在“QToolButton”的两侧放置两个间隔符可以放置布局代码和间隔符,也可以放置布局。@eyllanesc我编辑了我的答案,也许现在您可以看到问题所在。我把我所有的布局放在一个中心部件上。@eyllanesc我尝试了你的解决方案,它解决了我的第一个问题。还有一个问题,如果我仍然希望toolbutton随窗口展开,该怎么办?在您的解决方案中,展开时,文本只会向左移动,图标会向右移动。当它展开时,让文本和图标对齐中心是否可行?
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);