今天总结一下AbstractButton类的学习笔记。
一.描述
AbstractButton是对各种按键的抽象类他的继承关系是这样的
首先,QAbstractButton继承了QWidget类的各种用法;
其次,QAbstractButton是将各种按钮中共同存在的特性、功能抽象出来组成了一个类。所以他是所有按钮类的基类,提供了按钮的通用功能。但是由于他是给抽象类,不能直接实例化
from PyQt5.Qt import * import sys app=QApplication(sys.argv) window = QWidget() btn = QAbstractButton(window) window.show() sys.exit(app.exec_())
运行后发现有这样的提示
btn = QAbstractButton(window) TypeError: PyQt5.QtWidgets.QAbstractButton represents a C++ abstract class and cannot be instantiated
所以,在调用QAbstractButton时有两种方法:
1.对QAbstractButton进行子类化并对其所有方法重构
from PyQt5.Qt import * from PyQt5 import QtGui import sys app=QApplication(sys.argv) window = QWidget() class Btn(QAbstractButton): def paintEvent(self, e: QtGui.QPaintEvent): #对按钮进行绘制 painter = QPainter(self) pen = QPen(QColor(128,0,255),30) #设置笔QPen(QColor(RGB),笔粗细) painter.setPen(pen) painter.drawText(30,30,'画文本') def mousePressEvent(self, e: QtGui.QMouseEvent): #定义按键按下时的事件 print('按钮点击') btn = Btn(window) window.show() sys.exit(app.exec_())