I have written a class to display rectangles (the cell class). I would like to have functions inside the class to call in another class (i.e. calling cell.paintEvent(s
Well, you would need to import the cell object. To that you need to
from yourFileNameWithCellObject import cell
To initialize a cell, you simply need to do
newCell = cell(args_here)
or to make the newCell as a part of self (Window)
self.newCell = cell(args_here)
To call methods in the cell object is quite simple.
self.newCell.paintEvent(args_here)
The paintEvent method must be overwritten by the classes that inherit from QWidget. You can implement the function drawRectangles but you must invoke the paintEvent method using update() method.
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_())