子分类QPushButton
正如 @Pavel 在评论中所建议的,似乎是解决您的问题的合理选择。下面我提供了一个简单的示例,展示了如何在PySide
.
import sys
from PySide import QtGui, QtCore
class myContainter(QtGui.QWidget):
def __init__(self, parent=None):
super(myContainter, self).__init__(parent)
icon = QtGui.QIcon('process-stop.png')
grid = QtGui.QGridLayout()
for i in range(3):
button = myPushButton()
button.setIcon(icon)
grid.addWidget(button, i, 0)
grid.setRowStretch(i, i)
self.setLayout(grid)
class myPushButton(QtGui.QPushButton):
def __init__(self, label=None, parent=None):
super(myPushButton, self).__init__(label, parent)
self.pad = 4 # padding between the icon and the button frame
self.minSize = 8 # minimum size of the icon
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self.setSizePolicy(sizePolicy)
def paintEvent(self, event):
qp = QtGui.QPainter()
qp.begin(self)
#---- get default style ----
opt = QtGui.QStyleOptionButton()
self.initStyleOption(opt)
#---- scale icon to button size ----
Rect = opt.rect
h = Rect.height()
w = Rect.width()
iconSize = max(min(h, w) - 2 * self.pad, self.minSize)
opt.iconSize = QtCore.QSize(iconSize, iconSize)
#---- draw button ----
self.style().drawControl(QtGui.QStyle.CE_PushButton, opt, qp, self)
qp.end()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
instance = myContainter()
instance.show()
sys.exit(app.exec_())
结果是:
图标的最大尺寸受屏幕尺寸的限制png
用作输入QIcon
. If a svg
用作输入QIcon
,图标的缩放不会受到大小限制。不过,svg图标在Windows7中似乎不支持,但在Ubuntu中是支持的。
如果将标签添加到按钮,则需要扩展上面的代码。此外,如果需要,还可以将标签的字体大小缩放到按钮大小。