我正在使用多个 QToolButton s 自定义 QGridLayout小部件。这些按钮被设置为根据指定的默认 QAction 显示图标 + 文本。唯一的问题是内容(图标 + 文本)始终左对齐。
内容(图标+文本,在截图中标记为红色框),应位于按钮的中心(由蓝色框指示)。
对于大多数情况,这很好,因为 Qt 会自动尝试以最小尺寸呈现该按钮。但是我正在拉伸(stretch)按钮以很好地适应我的 QGridLayout。
QToolButton* pButton = new QToolButton(0);
pButton->addDefaultAction(pAction);
pButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
pButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
QGridLayout *pActionAreaLayout = new QGridLayout;
pActionAreaLayout->addWidget(pSomeOtherWidget, 0, 0, 1, 2);
pActionAreaLayout->addWidget(pButton , 1, 0, 1, 1);
有没有办法强制内容在按钮中居中?
PS:我在 another forum 中发现了以下评论,然而这似乎非常具有侵略性,我还不是很清楚:
You can try doing the horizontal alignment using a stylesheet, but you probably have to implement a QStyle proxy and reimplement drawControl() for QStyle::CE_ToolButtonLabel Or derive from QToolButton, overwrite paintEvent() and call the style for everything other than the label.
最佳答案
正如我在回答你另一个问题时所建议的那样。 https://stackoverflow.com/a/28630318/1917249不要使用 QToolButton,只需使用 QPushButton,并根据需要添加弹出菜单。
那么你不会有不同大小的 QToolButton
和 QPushButton
小部件。您将拥有居中的图标和文本。
弹出菜单可以很容易地添加到 QPushButton(只有小箭头不会显示)
QPushButton *pushButton = new QPushButton(toolAction->icon(), "PushButton", window);
// window - widget where button is placed ( to get correct QMenu position )
QObject::connect(pushButton, &QPushButton::released, [window, pushButton, action](){
QMenu menu;
menu.addAction(action);
QPoint pos = window->mapToGlobal(pushButton3->pos());
pos += QPoint(0, pushButton->height());
menu.exec(pos);
});
或者你可以子类
QPushButton
并在那里添加弹出菜单处理。最好尝试将文本与 QToolButton
中的图标居中或具有相同大小的 QPushButton
和 QToolButton
复杂的例子请看我的回答:https://stackoverflow.com/a/28630318/1917249
关于QToolButton 带图标 + 文本 : How to center both?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28516012/