如何更改默认选定项边框矩形?
How to change default selected item border rectange?
我发现QGraphicsEllipseItem
、QGraphicsRectItem
等项在选中时,Qt会在其周围画一个白色的点状矩形边框(如下图)。Qt的地方也是QWidget
或使用 paint
方法在它周围画一个矩形?
有时我想用其他 style.for 示例更改点白矩形,我想更改它的边框颜色、线条样式(线宽、线条颜色等)甚至它的形状,我阅读了 Qt 文档,没有找到执行此操作的方法,那么如何更改它的默认选定边框?
您必须覆盖 paint
方法:
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()
我发现QGraphicsEllipseItem
、QGraphicsRectItem
等项在选中时,Qt会在其周围画一个白色的点状矩形边框(如下图)。Qt的地方也是QWidget
或使用 paint
方法在它周围画一个矩形?
有时我想用其他 style.for 示例更改点白矩形,我想更改它的边框颜色、线条样式(线宽、线条颜色等)甚至它的形状,我阅读了 Qt 文档,没有找到执行此操作的方法,那么如何更改它的默认选定边框?
您必须覆盖 paint
方法:
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()