Replacing QTextEdit bounding box with a line

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

This question is a slight modification of the bounding box example. I'm trying to understand how to draw simple shapes. I just want to replace the bounding box with a diagonal line from the upperLeft point to the lowerRight point. However, QLine() does not appear to have a show() method and viewport() has no addItem() method. So, I think the line is not being displayed. Here is my modification of the showBoxes method:

def showLines(self):     while self.boxes:         self.boxes.pop()            #self.boxes.pop().deleteLater()                                     #Qline has no deleteLater(). Does that matter?     viewport = self.edit.viewport()     for start, end, ident in db:         rect = self.edit.getBoundingRect(start, end)         x = rect.x()         y = rect.y()         h = rect.height()         w = rect.width()         line = QLine()             #QRubberBand(QRubberBand.Rectangle, viewport)         line.setLine(x,y,x+w,y+h)  #box.setGeometry(rect)         # need to show line here?         self.boxes.append(line) 

回答1:

One possible solution is to replace QRubberBand with another widget that draws the diagonal, to create a class that inherits from QWidget and overwrite the paintEvent method.

class Window(QWidget):     def __init__(self):         super(Window, self).__init__()         self.edit = TextEditor(self)         layout = QVBoxLayout(self)         layout.addWidget(self.edit)         self.boxes = []      def showBoxes(self):         while self.boxes:             self.boxes.pop().deleteLater()         viewport = self.edit.viewport()         for start, end, ident in db:             rect = self.edit.getBoundingRect(start, end)             box = LineBand(viewport)             box.setGeometry(rect)             box.show()             self.boxes.append(box)      def resizeEvent(self, event):         self.showBoxes()         super().resizeEvent(event)   class LineBand(QWidget):     def  paintEvent(self, event):         painter = QPainter(self)         painter.setRenderHint(QPainter.Antialiasing)         painter.setPen(QPen(Qt.black, 1.8))         painter.drawLine(self.rect().topLeft(), self.rect().bottomRight()) 



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