Draw vertical lines on QTextEdit in PyQt

≡放荡痞女 提交于 2019-12-08 07:04:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!