如下代码所示,我想在一个Dialog的Qwidget里绘制一个矩形,但在发送信号调用DrawRec的时候并没有绘制出图形,但是把DrawRec放在paintEvent里就能绘制出来,难道Qwidget只能在paintEvent里绘制图形?还是因为我没能正确调用呢?
import sys
from PyQt5.QtCore import pyqtSlot, pyqtSignal
from PyQt5.QtWidgets import QApplication, QDialog,QWidget, QVBoxLayout
from PyQt5.QtGui import QPainter, QColor, QBrush, QPen, QPalette
class myWidget(QWidget):
def __init__(self):
super().__init__()
self.setBackgroundRole(QPalette.Midlight)
self.setAutoFillBackground(True)
def paintEvent(self, e):
# self.DrawRec(10, 10, 50, 50)
pass
@pyqtSlot(int, int, int, int) # 定义槽函数
def DrawRec(self, x1, y1, x2, y2):
qp = QPainter()
qp.begin(self)
col = QColor(0, 0, 0)
col.setNamedColor('#d4d4d4')
qp.setPen(col)
qp.setBrush(QColor(200, 0, 0))
qp.drawRect(x1, y1, x2, y2)
qp.end()
class Dialog(QDialog):
_signal = pyqtSignal(int, int, int, int) # 定义信号
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setObjectName("Dialog")
self.resize(400, 300)
self.setSizeGripEnabled(True)
wigglyWidget = myWidget()
layout = QVBoxLayout()
layout.addWidget(wigglyWidget)
self.setLayout(layout)
self._signal.connect(wigglyWidget.DrawRec) # connect
self._signal.emit(20, 20, 50, 50) # 信号发送
if __name__ == "__main__":
app = QApplication(sys.argv)
dlg = Dialog()
dlg.show()
sys.exit(app.exec_())