我编写了一个类来显示矩形(单元格类)。我希望类内部有函数可以在另一个类中调用(即在一个类中调用 cell.paintEvent(self,event) 和 cell.drawRectangles(self,qp) Window 类中定义的函数)。不幸的是,我不知道如何在另一个类(即 Window)中调用这些函数,因为它们都需要参数(即 event
和 pq
),而且我不知道该做什么传递给他们。
这是我的细胞类的代码:
class cell(object):
def __init__(self, c, x, y, w, h, active,flux_val,index):
self.c1 = c
self.c2 = c
self.c3 = 255
self.x = x
self.y = y
self.w = w
self.h = h
self.index = index
self.active = active
self.flux_val = flux_val
self.isChecked = False
self.isHit = False
def paintEvent(self, e):
qp = QtGui.QPainter()
qp.begin(self)
self.drawRectangles(qp)
qp.end()
def drawRectangles(self, qp):
color = self.c2
#qp.setPen(color)
qp.setBrush(color)
qp.drawRect(self.x, self.y, self.w, self.h)
这是代码的一部分(特别是def.initiate(self)
),我想在其中实例化单元格对象数组(我可以轻松做到),然后调用其相关的显示函数(即 cell.paintEvent(self,event)
和 cell.drawRectangles(self,qp)
,我仍然不知道该怎么做):
import sys
from PyQt4 import QtGui, QtCore
import numpy as np
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 1000, 800)
self.setWindowTitle("PyQT tuts!")
self.initiate()
self.show()
def initiate(self):
#initiate an array of cell objects
#Call their display functions (or any other relevant class functions)
最佳答案
paintEvent
方法必须由继承自 QWidget 的类覆盖。您可以实现函数 drawRectangles
,但必须使用 update()
方法调用 paintEvent
方法。
import sys
from PyQt4 import QtGui, QtCore
class cell(object):
def __init__(self, c, x, y, w, h):
self.color = c
self.x = x
self.y = y
self.w = w
self.h = h
def drawRectangles(self, qp):
qp.setBrush(self.color)
qp.drawRect(self.x, self.y, self.w, self.h)
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 1000, 800)
self.setWindowTitle("PyQT tuts!")
self.cells = []
now = QtCore.QTime.currentTime()
QtCore.qsrand(now.msec())
self.createCells()
def createCells(self):
for i in range(100):
self.cells.append(cell(QtGui.QColor(QtCore.qrand() % 256,
QtCore.qrand() % 256,
QtCore.qrand() % 256),
QtCore.qrand() % self.width(), QtCore.qrand() % self.height(),
QtCore.qrand() % 40, QtCore.qrand() % 40))
self.update()
def paintEvent(self, e):
qp = QtGui.QPainter(self)
for c in self.cells:
c.drawRectangles(qp)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())
关于python - 从 pyqt4 python 中的类调用paintEvent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41116234/