Python 在对话框中画图

Drawing graph in the dialogue box in Python

我尝试编写一个程序,使用 PyQt5 和 pyqtgraph 在对话框中绘制图形。该程序应该创建一个带有按钮的 window。按下该按钮应该会生成另一个带有绘制图形的 window。我写了这段代码:

import PyQt5.QtWidgets as pq
import pyqtgraph as pg

class MainWindow():
    def __init__(self):
        self.app = pq.QApplication([])
        self.window = pq.QWidget()
        self.window.setFixedSize(500,300)
        self.layout = pq.QGridLayout()

        self.button_manual = pq.QPushButton('Draw')
        self.button_manual.clicked.connect(self.draw_manual)

        self.layout.addWidget(self.button_manual)
        self.window.setLayout(self.layout)

        self.window.show()
        self.app.exec_()

    def draw_manual(self):
        x = [1,2,3,4,5,6,7,8,9,10]
        y = [30,32,34,32,33,31,29,32,35,45]
        dialog = Dialog(x,y)
        dialog.exec_()

class Dialog(pq.QDialog):
    def __init__(self,x,y):
        super(Dialog,self).__init__()
        self.app = pq.QApplication([])
        self.main = draw_graph(x,y)
        self.main.show()

class draw_graph(pq.QMainWindow):
    def __init__(self,x,y):
        pq.QMainWindow.__init__(self)
        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)
        self.graphWidget.plot(x,y)

MainWindow()

首先编译代码后 window 会正确弹出,但在按下按钮后会创建两个 windows - 一个具有正确绘制的图形,一个为空。关闭空 window 后,应用程序崩溃。

有人可以指出我做错了什么以及如何解决吗?谢谢

我修改了你的代码,查看代码中的注释了解更多详情:

import PyQt5.QtWidgets as pq
import pyqtgraph as pg

class MainWindow(pq.QWidget):
    def __init__(self):
        pq.QWidget.__init__(self)
        self.setFixedSize(500, 300)
        self.layout = pq.QGridLayout()
        
        self.button_manual = pq.QPushButton('Draw')
        self.button_manual.clicked.connect(self.draw_manual)
        
        self.layout.addWidget(self.button_manual)
        self.setLayout(self.layout)
        
        self.show()
    
    def draw_manual(self):
        y = [30, 32, 34, 32, 33, 31, 29, 32, 35, 45]
        x = range(1, len(y) + 1) # when you change y values, x will automatically have the correct x values
        dialog = Dialog(x, y) # create the dialog ...
        dialog.exec_() # ... and show it

class Dialog(pq.QDialog):
    def __init__(self, x, y):
        pq.QDialog.__init__(self)
        self.layout = pq.QHBoxLayout() # create a layout to add the plotwidget to
        self.graphWidget = pg.PlotWidget()
        self.layout.addWidget(self.graphWidget) # add the widget to the layout
        self.setLayout(self.layout) # and set the layout on the dialog
        self.graphWidget.plot(x, y)

if __name__ == "__main__": # if run as a program, ad not imported ...
    app = pq.QApplication([]) # create ONE application (in your original code you had two, thats why it crashed)
    win = MainWindow() # create the main window
    app.exec_() # run the app

最重要的:你不能创造两个 QApplication 的实例!这将 总是 导致崩溃!
此外,我简化了您的 MainWindow class,它现在继承自 QWidget 而不是创建一个作为成员。当您更改 y 数组时,x 值数组现在将自动具有正确的值。
此代码已经过测试并且可以正常工作。