用一行替换QTextEdit边界框

时间:2017-11-03 08:19:11

标签: python pyside qtextedit

这个问题是bounding box示例的略微修改。我试图了解如何绘制简单的形状。我只想用从左上点到下右点的对角线替换边界框。但是,QLine()似乎没有show()方法,viewport()没有addItem()方法。所以,我认为这条线没有显示出来。这是我对showBoxes方法的修改:

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 个答案:

答案 0 :(得分:1)

一种可能的解决方案是将QRubberBand替换为绘制对角线的另一个窗口小部件,以创建一个继承自QWidget并覆盖paintEvent方法的类。

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())

enter image description here