,可以通过以下步骤实现:
这样,当用户在组合框中选择不同的选项时,主窗口上的绘图区域会显示相应的图形。
以下是一个示例代码,演示如何在PyQt图形用户界面上选择组合框选项时,在现有主窗口上显示图形:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QComboBox, QVBoxLayout, QWidget
from PyQt5.QtGui import QPainter, QPen, QColor
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt Graph")
# 创建组合框控件
self.combo_box = QComboBox()
self.combo_box.addItem("Rectangle")
self.combo_box.addItem("Circle")
self.combo_box.addItem("Line")
self.combo_box.currentIndexChanged.connect(self.updateGraph)
# 创建绘图区域
self.graph_widget = QWidget()
self.graph_widget.setMinimumSize(400, 400)
# 创建布局管理器
layout = QVBoxLayout()
layout.addWidget(self.combo_box)
layout.addWidget(self.graph_widget)
# 创建主窗口中心部件
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def updateGraph(self):
# 获取选中的选项
selected_option = self.combo_box.currentText()
# 创建绘图对象
painter = QPainter(self.graph_widget)
painter.setRenderHint(QPainter.Antialiasing)
# 清空绘图区域
painter.fillRect(self.graph_widget.rect(), Qt.white)
# 根据选项绘制图形
if selected_option == "Rectangle":
painter.setPen(QPen(Qt.black, 2))
painter.drawRect(50, 50, 200, 100)
elif selected_option == "Circle":
painter.setPen(QPen(Qt.red, 2))
painter.drawEllipse(100, 100, 150, 150)
elif selected_option == "Line":
painter.setPen(QPen(Qt.blue, 2))
painter.drawLine(50, 200, 250, 200)
# 刷新绘图区域
self.graph_widget.update()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
在这个示例中,我们创建了一个主窗口应用程序,其中包含一个组合框控件和一个绘图区域。当用户在组合框中选择不同的选项时,绘图区域会显示相应的图形(矩形、圆形或直线)。
领取专属 10元无门槛券
手把手带您无忧上云