class CanvasView(QGraphicsView):
def __init__(self, scene, parent=None):
super().__init__(scene, parent)
# 设置样式,不然会有滚动条
self.setStyleSheet("padding:0px;border:0px")
self.setAlignment(Qt.AlignLeft | Qt.AlignTop)
class MyWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.scene = QGraphicsScene(self)
self.m_view = CanvasView(self.scene, self)
self.m_view.setGeometry(0, 0, 800, 600)
self.scene.setSceneRect(0, 0, self.m_view.width(), self.m_view.height())
pen = QPen()
pen.setColor(Qt.blue)
pen.setWidth(1)
brush = QBrush(Qt.SolidPattern)
brush.setColor(Qt.yellow)
self.scene.addRect(0, 0, 800, 600, pen, brush)
if __name__ == "__main__":
app = QApplication(sys.argv)
wid = MyWidget()
wid.setGeometry(100, 100, 800, 600)
wid.show()
app.exec_()