我有一个名为TwoStateButton的类,该类继承QPushButton,以便在单击按钮时可以更改图标,因此在调整整个窗口的大小时,图标的大小与按钮的大小成比例。
运行此代码时,按钮占据整个窗口,并且图标大约占按钮的10%。我试图获取它,以使图标图像占据整个按钮,并且在调整窗口大小时,它们都被调整为相同的大小。
我应该对我的代码进行哪些修改以实现此目的?
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class TwoStateButton(QtWidgets.QPushButton):
def __init__(self, on, hover, parent=None):
super(TwoStateButton, self).__init__(parent)
self.pad = 4 # padding between the icon and the button frame
self.minSize = 8 # minimum size of the icon
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
)
self.setSizePolicy(sizePolicy)
self.setIcon(QtGui.QIcon(on))
self.on = on
self.hover = hover
def mousePressEvent(self, event):
super(TwoStateButton, self).mousePressEvent(event)
self.setIcon(QtGui.QIcon(self.hover))
def mouseReleaseEvent(self, event):
super(TwoStateButton, self).mouseReleaseEvent(event)
self.setIcon(QtGui.QIcon("%s" % (self.on)))
def paintEvent(self, event):
qp = QtGui.QPainter(self)
opt = QtWidgets.QStyleOptionButton()
self.initStyleOption(opt)
r = opt.rect
h = r.height()
w = r.width()
iconSize = max(min(h, w) - 2 * self.pad, self.minSize)
opt.iconSize = QtCore.QSize(iconSize, iconSize)
self.style().drawControl(QtWidgets.QStyle.CE_PushButton, opt, qp,self)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1090, 681)
MainWindow.setStyleSheet("")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton_2 = TwoStateButton(
"images/Button5-3.png", "images/Button5-4.png", self.centralwidget
)
self.pushButton_2.setGeometry(QtCore.QRect(430, 310, 141, 81))
self.pushButton_2.setText("")
self.pushButton_2.setCheckable(False)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1090, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setStyleSheet(
"border-image: url(:/images/Button5-3.png)"
)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())