我一直在尝试使用python语言的pyqt5 GUI创建一个带有图像背景和两个按钮(取消和确定)的小部件,带有图像和下推/上推效果,但我有两个问题:
1 – 我无法对齐小部件中心的按钮
2 – 按钮事件发生两次
代码:
import sys
from PyQt5 import QtGui
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class PicButton(QAbstractButton):
def __init__(self, pixmap, pixmap_pressed, id_button, parent=None):
super(PicButton, self).__init__(parent)
self.pixmap = pixmap
self.pixmap_pressed = pixmap_pressed
self.id_buton = id_button
self.pressed.connect(self.update)
self.released.connect(self.update)
def paintEvent(self, event):
if self.isDown():
pix = self.pixmap_pressed
print("botao pressionado: ", self.id_buton)
else:
pix = self.pixmap
painter = QPainter(self)
painter.drawPixmap(event.rect(), pix)
def enterEvent(self, event):
self.update()
def leaveEvent(self, event):
self.update()
def sizeHint(self):
return QSize(131, 82)
app = QApplication(sys.argv)
window = QWidget()
window.setGeometry(800, 450, 800, 450)
pixmap = QPixmap("background.png")
brush = QBrush(pixmap)
palette = QPalette()
palette.setBrush(QPalette.Background, brush)
window.setPalette(palette)
button1 = PicButton(QtGui.QPixmap("cancel_up.png"), QtGui.QPixmap("cancel_down.png"), "cancel")
button2 = PicButton(QtGui.QPixmap("ok_up.png"), QtGui.QPixmap("ok_down.png"), "ok")
layout = QHBoxLayout()
layout.addStretch(1)
layout.addWidget(button1)
layout.addWidget(button2)
layout.setAlignment(Qt.AlignCenter)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
在链接中获取图片:https ://www.filedropper.com/imagens
有人可以告诉我我做错了什么吗?