我试图编写一个使用PyQt5和pyqtgraph在对话框中绘制图形的程序。该程序应创建一个带有按钮的窗口。按下该按钮将产生另一个带有绘制图形的窗口。我写了这段代码:
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()
编译代码后,第一个窗口将正确弹出,但是在按下按钮后,它将创建两个窗口-一个窗口具有正确绘制的图形,另一个窗口为空。关闭空窗口后,应用程序崩溃。
有人可以指出我在做什么错以及如何解决吗?谢谢。
我已修复您的代码,请参阅代码中的注释以获取更多详细信息:
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类,现在它继承自QWidget,而不是将其创建为成员。现在,当您更改y数组时,x values数组将自动具有正确的值。
此代码已经过测试,可以正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句