pyqt5 绘制拓扑图
时间: 2024-01-03 13:20:48 浏览: 103
要在PyQt5中绘制拓扑图,可以使用QGraphicsView和QGraphicsScene类。QGraphicsView是一个用于显示QGraphicsScene的窗口部件,而QGraphicsScene是一个用于管理2D图形项的场景。以下是一个简单的示例代码,用于绘制一个简单的拓扑图:
```python
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
class Node(QGraphicsItem):
def __init__(self, name):
super().__init__()
self.name = name
self.edges = []
def addEdge(self, edge):
self.edges.append(edge)
def boundingRect(self):
return QRectF(-25, -25, 50, 50)
def paint(self, painter, option, widget):
painter.drawEllipse(-25, -25, 50, 50)
painter.drawText(-10, 10, self.name)
class Edge(QGraphicsItem):
def __init__(self, source, dest, weight=None):
super().__init__()
self.source = source
self.dest = dest
self.source.addEdge(self)
self.dest.addEdge(self)
self.weight = weight
def boundingRect(self):
return QRectF()
def paint(self, painter, option, widget):
painter.drawLine(self.source.pos(), self.dest.pos())
if self.weight is not None:
painter.drawText((self.source.pos() + self.dest.pos()) / 2, str(self.weight))
class Graph(QGraphicsScene):
def __init__(self, adjacency_matrix):
super().__init__()
self.nodes = []
self.edges = []
for i in range(len(adjacency_matrix)):
node = Node(str(i))
self.addItem(node)
node.setPos(100 * i, 100)
self.nodes.append(node)
for i in range(len(adjacency_matrix)):
for j in range(i, len(adjacency_matrix)):
if adjacency_matrix[i][j] != 0:
edge = Edge(self.nodes[i], self.nodes[j], adjacency_matrix[i][j])
self.addItem(edge)
self.edges.append(edge)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.view = QGraphicsView(self)
self.setCentralWidget(self.view)
self.scene = Graph([[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]])
self.view.setScene(self.scene)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
该代码将绘制一个简单的无向图,其中节点用圆圈表示,边用线段表示。节点和边都是QGraphicsItem的子类,可以通过重写boundingRect()和paint()方法来自定义它们的外观。Graph类将邻接矩阵转换为节点和边,并将它们添加到QGraphicsScene中。MainWindow类创建一个QGraphicsView并将QGraphicsScene设置为其场景。运行该代码将显示一个简单的拓扑图。
阅读全文