[PyQt] Drawing on a QFrame
Phil
phil_lor at bigpond.com
Fri Jun 28 10:31:10 BST 2013
On 28/06/13 18:56, Phil Thompson wrote:
> On Fri, 28 Jun 2013 15:35:20 +1000, Phil <phil_lor at bigpond.com> wrote:
>> Thank you for reading this.
>>
>> I'd like to draw on a QFrame.
>>
>> The following does draw a line but not on the frame, instead the line is
>
>> drawn on the main window.
>>
>> I've done this years ago with Qt and C++ but I don't remember how I did
> it.
>>
>> class DrawTest(QtGui.QMainWindow):
>> def __init__(self, parent=None):
>> super(DrawTest, self).__init__(parent)
>> self.ui = Ui_MainWindow()
>> self.ui.setupUi(self)
>> frame = QtGui.QFrame()
>>
>> def paintEvent(frame, event):
>> qp = QtGui.QPainter()
>> qp.begin(frame)
>> pen = QtGui.QPen(QtCore.Qt.yellow, 4)
>> qp.setPen(pen)
>> frame.drawLine(event, qp)
>> qp.end()
>>
>> def drawLine(frame, event, qp):
>> qp.drawLine(10, 10, 30, 30)
>
> Sub-class the frame and reimplement its paintEvent(). Also make sure the
> frame isn't being garbage collected (like it is above) and add it to the
> GUI somewhere.
>
Thank you Rob and Phil,
It's still not totally clear to me. Say for example, that I want to
display a frame on the main window and draw a red line on the frame and,
through another function, draw a yellow line on the main window.
I've added the extra class as Rob has suggested but I'm not getting the
result that I expect. The Frame class would be a separate module but
I've put the two classes in the same module for this example.
class DrawTest(QtGui.QMainWindow):
def __init__(self, parent=None):
super(DrawTest, self).__init__(parent)
If I comment out the following two lines then I get a red line on the
frame but only the frame is displayed without the main window.
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
If I comment out the following two lines then, of course, I'm back to
where I started with a yellow line on the main window and the empty
frame is displayed.
self.frame = Frame(self)
self.setCentralWidget(self.frame)
def buttonClicked(self):
print("clicked")
def paintEvent(self, event):
qp = QtGui.QPainter()
qp.begin(self)
pen = QtGui.QPen(QtCore.Qt.yellow, 4)
qp.setPen(pen)
self.drawLine(event, qp)
qp.end()
def drawLine(self, event, qp):
qp.drawLine(10, 10, 30, 30)
class Frame(QtGui.QFrame):
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.setPen(QtGui.QPen(QtCore.Qt.red, 4))
qp.drawLine(10,10,30,30)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
mySW = DrawTest()
mySW.show()
sys.exit(app.exec_())
--
Regards,
Phil
More information about the PyQt
mailing list