首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在QPushButton中对齐图标

在QPushButton中对齐图标
EN

Stack Overflow用户
提问于 2020-11-04 08:39:17
回答 2查看 539关注 0票数 0

启动程序时,QIcon与右边的文本对齐(我猜这是标准的)。

相反,我希望图标在顶部居中,下面是文本。

我尝试将setStyleSheetshow_all.setStyleSheet("QIcon { vertical-align: top }")show_all.setStyleSheet("QPushButton { text-align: bottom }")结合使用。

我怎样才能做到这一点?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-11-04 13:20:04

QPushButton不允许选择其图标和标签的布局。另外,请记住,虽然Qt特性样式表用于样式小部件,但并不是所有的CSS已知属性和选择器都可用。此外,样式表只适用于小部件,因此不支持使用QIcon选择器,因为QIcon不是QWidget子类。

最简单的解决方案是使用QToolButton并正确设置toolButtonStyle

代码语言:javascript
运行
复制
self.someButton = QtWidgets.QToolButton()
# ...
self.someButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)

另一种方法是对按钮进行子类化,提供自定义的画图方法,并重新实现sizeHint()paintEvent();第一种方法是确保该按钮能够在需要时自行调整大小,而第二种方法是绘制按钮控件(没有文本!)然后绘制图标和文本。

以下是一个可能的实现:

代码语言:javascript
运行
复制
from PyQt5 import QtCore, QtGui, QtWidgets

class CustomButton(QtWidgets.QPushButton):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._icon = self.icon()
        if not self._icon.isNull():
            super().setIcon(QtGui.QIcon())

    def sizeHint(self):
        hint = super().sizeHint()
        if not self.text() or self._icon.isNull():
            return hint
        style = self.style()
        opt = QtWidgets.QStyleOptionButton()
        self.initStyleOption(opt)
        margin = style.pixelMetric(style.PM_ButtonMargin, opt, self)
        spacing = style.pixelMetric(style.PM_LayoutVerticalSpacing, opt, self)
        # get the possible rect required for the current label
        labelRect = self.fontMetrics().boundingRect(
            0, 0, 5000, 5000, QtCore.Qt.TextShowMnemonic, self.text())
        iconHeight = self.iconSize().height()
        height = iconHeight + spacing + labelRect.height() + margin * 2
        if height > hint.height():
            hint.setHeight(height)
        return hint

    def setIcon(self, icon):
        # setting an icon might change the horizontal hint, so we need to use a 
        # "local" reference for the actual icon and go on by letting Qt to *think*
        # that it doesn't have an icon;
        if icon == self._icon:
            return
        self._icon = icon
        self.updateGeometry()

    def paintEvent(self, event):
        if self._icon.isNull() or not self.text():
            super().paintEvent(event)
            return
        opt = QtWidgets.QStyleOptionButton()
        self.initStyleOption(opt)
        opt.text = ''
        qp = QtWidgets.QStylePainter(self)
        # draw the button without any text or icon
        qp.drawControl(QtWidgets.QStyle.CE_PushButton, opt)

        rect = self.rect()
        style = self.style()
        margin = style.pixelMetric(style.PM_ButtonMargin, opt, self)
        iconSize = self.iconSize()
        iconRect = QtCore.QRect((rect.width() - iconSize.width()) / 2, margin, 
            iconSize.width(), iconSize.height())
        if self.underMouse():
            state = QtGui.QIcon.Active
        elif self.isEnabled():
            state = QtGui.QIcon.Normal
        else:
            state = QtGui.QIcon.Disabled
        qp.drawPixmap(iconRect, self._icon.pixmap(iconSize, state))

        spacing = style.pixelMetric(style.PM_LayoutVerticalSpacing, opt, self)
        labelRect = QtCore.QRect(rect)
        labelRect.setTop(iconRect.bottom() + spacing)
        qp.drawText(labelRect, 
            QtCore.Qt.TextShowMnemonic|QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop, 
            self.text())


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = CustomButton('Alles anzeigen', icon=QtGui.QIcon.fromTheme('document-new'))
    w.setIconSize(QtCore.QSize(32, 32))
    w.show()
    sys.exit(app.exec_())
票数 2
EN

Stack Overflow用户

发布于 2020-11-04 14:18:31

或者,试一试:

代码语言:javascript
运行
复制
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout,  
    QToolBar, QAction) 


class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        
        add_action = QAction(QIcon("img/add.png"), "Add", self)      
        add_action.triggered.connect(self.addValue)
        sub_action = QAction(QIcon("img/min.png"), "Sub", self)    
        sub_action.triggered.connect(self.subValue)

        toolbar = QToolBar()
        toolbar.setContentsMargins(0, 0, 0, 0)
        toolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon | Qt.AlignLeading)
        toolbar.setIconSize(QSize(50, 50))
        toolbar.addAction(add_action)
        toolbar.addAction(sub_action)

        rootGrid = QGridLayout(self)
        rootGrid.addWidget(toolbar)

    def addValue(self):
        print("def addValue:")

    def subValue(self):
        print("def subValue:")
       

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = Widget()
    main.show()
    sys.exit(app.exec_())

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64676618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档