Home > Mobile >  How to change default selected item border rectange?
How to change default selected item border rectange?

Time:05-17

I found QGraphicsEllipseItem, QGraphicsRectItem and other items when them was selected,The Qt will draw a dotted-white rectangel border around it(like the picture bellow).So is that Qt place a QWidget or use paint method draw a rectange around it? And sometime I want to change dotted-white rectangel with other style.for example, I want to change it border color, line style(line-width, line-color and so on) or even it's shape,I read Qt doc, not found method to do this, So How Can I change it's default selected border ?

enter image description here

CodePudding user response:

You must override the paint method:

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QPen
from PyQt5.QtWidgets import (
    QApplication,
    QGraphicsEllipseItem,
    QGraphicsItem,
    QGraphicsScene,
    QGraphicsView,
    QStyle,
)


class EllipseItem(QGraphicsEllipseItem):
    def paint(self, painter, option, widget):
        is_selected = option.state & QStyle.State_Selected
        # Remove default paint from selection
        option.state &= ~QStyle.State_Selected
        super().paint(painter, option, widget)

        if is_selected:
            # custom paint
            itemPenWidth = self.pen().widthF()
            pad = itemPenWidth / 2
            penWidth = 0
            bgcolor = QColor("salmon")
            painter.setPen(QPen(bgcolor, penWidth, Qt.SolidLine))
            painter.setBrush(Qt.NoBrush)
            painter.drawRect(self.boundingRect().adjusted(pad, pad, -pad, -pad))
            painter.setPen(QPen(QColor("blue"), 0, Qt.DashLine))
            painter.setBrush(Qt.NoBrush)
            painter.drawRect(self.boundingRect().adjusted(pad, pad, -pad, -pad))


def main():
    app = QApplication([])

    scene = QGraphicsScene()

    ellipse_item = EllipseItem(0, 0, 500, 500)
    ellipse_item.setBrush(QColor("white"))
    ellipse_item.setFlag(QGraphicsItem.ItemIsSelectable)
    scene.addItem(ellipse_item)

    view = QGraphicsView()
    view.setScene(scene)
    view.show()

    app.exec_()


if __name__ == "__main__":
    main()
  • Related