我正在尝试创建一个自定义 PyQt5 按钮,但在QMainWindow
对象中显示它时遇到问题。这是我正在尝试的代码:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QMainWindow
class PicButton(QAbstractButton):
def __init__(self, pixmap, parent=None):
super(PicButton, self).__init__(parent)
self.pixmap = pixmap
def paintEvent(self, event):
painter = QPainter(self)
painter.drawPixmap(event.rect(), self.pixmap)
def sizeHint(self):
return self.pixmap.size()
class App(QMainWindow):
def __init__(self):
super().__init__()
self.left = 0
self.top = 0
self.width = 800
self.height = 800
self.initUI()
def initUI(self):
self.setGeometry(self.left, self.top, self.width, self.height)
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.white)
self.setPalette(p)
btn = PicButton('/home/user/Desktop/Untitled.png')
btn.move(0, 0)
btn.resize(80,80)
self.show()
app = QApplication(sys.argv)
window = App()
如果您只是使用window = Widget()
并将按钮对象放入其中,则该按钮将起作用,如以下答案所示:如何在 PyQt 中编写图像按钮?