Calling paintEvent() from a class in pyqt4 python

前端 未结 2 1531
执念已碎
执念已碎 2020-12-12 00:21

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

相关标签:
2条回答
  • 2020-12-12 01:16

    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)
    
    0 讨论(0)
  • 2020-12-12 01:17

    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_())
    

    0 讨论(0)
提交回复
热议问题