我写了一个类来显示矩形(单元格类)。我希望在类中有函数来调用另一个类(即在Window类中定义的函数中调用cell.paintEvent(self,event)
和cell.drawRectangles(self,qp)
)。不幸的是,我不知道如何在另一个类(即Window)中调用这些函数,因为它们都需要参数(即event
和pq
)并且我不知道要传递给它们的内容。< / p>
以下是我的手机类的代码:
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)
答案 0 :(得分:1)
paintEvent
方法必须被从QWidget继承的类覆盖。您可以实现drawRectangles
功能,但必须在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_())
答案 1 :(得分:-1)
好吧,您需要导入单元格对象。为此你需要
from yourFileNameWithCellObject import cell
要初始化单元格,您只需要执行
newCell = cell(args_here)
或将newCell
作为self
(窗口)的一部分
self.newCell = cell(args_here)
调用单元格对象中的方法非常简单。
self.newCell.paintEvent(args_here)