问题
I am trying to develop a GUI that contains a QTextEdit widget. When the gui loads, it pulls in data from a file where the data is in columns of fixed widths.
I want the user to be able to click at various points in the QTextEdit widget, to mark the positions where new columns start, and I want vertical lines to be drawn on the widget at those positions, to show the columns.
In my GUI init() method I had the following line to intercept the paintEvent from the text widget:
self.mytextviewer.paintEvent = self.handlePaintEvent
and I had a handlePaintEvent() method:
def handlePaintEvent(self, event):
painter = QPainter(self.mytextviewer)
pen = QPen(Qt.SolidLine)
pen.setColor(Qt.black)
pen.setWidth(1)
painter.setPen(pen)
painter.drawLine(20, 0, 20, 100)
However when I tried to run the code I started to get QPainter errors about the painter not being active.
I then tried a different direction, subclassing QTextEdit and adding basically the same code as above to the paintEvent() method of my subclass. However I am still getting the errors.
I then tried adding painter.begin(self)
and painter.end()
to the paintEvent() method, but had no joy with that either.
Also, the text that was initially being displayed in the widget is no longer displayed since I added my custom paintEvent() method.
Am I doing something really stupid here, or is there a better/easier way to go about this?
Thanks.
回答1:
I found an answer, hopefully it might help someone else....
You need to supply QPainter with the widgets viewport when creating an instance of QPainter in the paintEvent().
To get it to display the text, include the super() method of the parent class.
def paintEvent(self, event):
painter = QPainter(self.viewport())
pen = QPen(Qt.SolidLine)
pen.setColor(Qt.black)
pen.setWidth(1)
painter.setPen(pen)
painter.drawLine(20, 0, 20, 100)
super(TextWidgetWithLines, self).paintEvent(event)
来源:https://stackoverflow.com/questions/30371613/draw-vertical-lines-on-qtextedit-in-pyqt