我正在制作一个纸牌游戏来练习 OOP 和 PyQt5,但我无法将继承 的卡片添加QAbstractButton
到布局(QGridLayout
、QHBoxLayout
或QVBoxLayout
)中。这是Card
对象的一部分:
class Card(QAbstractButton):
def __init__(self, rank=None, suit=None, parent=None):
super().__init__(parent)
self.rank = rank
self.suit = suit
self.visibility = False
def paintEvent(self, e):
painter = QPainter()
painter.begin(self)
if self.visibility == True:
self.draw_card_front(painter)
else:
self.draw_card_back(painter)
painter.end()
def draw_card_back(self, painter):
painter.setPen(COLOR_OUTLINE)
painter.setBrush(COLOR_BACK)
painter.drawRoundedRect(0, 0, CARD_WIDTH-1, CARD_HEIGHT-1, 10, 10)
def draw_card_front(self, painter):
painter.setPen(COLOR_OUTLINE)
painter.setBrush(COLOR_FRONT)
painter.drawRoundedRect(0, 0, CARD_WIDTH-1, CARD_HEIGHT-1, 10, 10)
self.draw_rank(painter)
self.draw_suit(painter)
...
这是游戏的类:
class Solitaire(QWidget):
def __init__(self):
super().__init__()
self.score = 0
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
self.card1 = Card(rank=1, suit=2, parent=self)
self.card2 = Card(rank=1, suit=2, parent=self)
grid.addWidget(self.card1, 0, 0)
grid.addWidget(self.card2, 1, 0)
self.setWindowTitle('Yay')
self.setGeometry(300, 300, 400, 400)
self.show()
...
if __name__ == '__main__':
app = QApplication(sys.argv)
game = Solitaire()
app.exec_()
当我运行程序时,Card
没有出现。但如果我不使用布局,则Card
正常显示。如果我尝试将 a 添加QPushButton
到布局中,它也可以正常工作。我觉得我缺少该parent
属性的某些内容,或者我没有从类QAbstractButton
中重载函数Card
。任何人都可以建议吗?