QToolButton 带图标 + 文本 : How to center both?

标签 qt qt5 text-alignment qstyle qstylesheet

我正在使用多个 QToolButton s 自定义 QGridLayout小部件。这些按钮被设置为根据指定的默认 QAction 显示图标 + 文本。唯一的问题是内容(图标 + 文本)始终左对齐。

内容(图标+文本,在截图中标记为红色框),应位于按钮的中心(由蓝色框指示)。

enter image description here

对于大多数情况,这很好,因为 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,并根据需要添加弹出菜单。

那么你不会有不同大小的 QToolButtonQPushButton小部件。您将拥有居中的图标和文本。

弹出菜单可以很容易地添加到 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 中的图标居中或具有相同大小的 QPushButtonQToolButton
复杂的例子请看我的回答:https://stackoverflow.com/a/28630318/1917249

关于QToolButton 带图标 + 文本 : How to center both?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28516012/

相关文章:

c++ - 仅使用 600 MB 内存时调整 QByteArray 的大小会抛出 std::bad_alloc

c++ - Qt-Creator 无法解析通用 Qt-project,但包含 OK

Qt QML 包含来自不同目录的问题

c++ - Qt 对象所有权内存泄漏

java - 如何在Java中将文本xTab空格的字符串 block 向右移动?

带有调试器的 QT

c++ - 动态创建的自定义 QML 对象不可见

qt - 如何在Qt5中更改TableView标题的颜色(背景,文本)?

pdf - 如何在 PDF 中设置水平或垂直对齐文本?

javascript - 更改下拉菜单文本对齐实现 1.0.0