简体   繁体   中英

Draw vertical lines on QTextEdit in PyQt

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM