0
用戶使用MyWidget
屏幕上的線編輯輸入值,然後按下Enter按鈕。這會打開MyDialog
屏幕,在按下「運行」按鈕時將在其上繪製數據。我怎樣才能讓線編輯數據訪問run
MyDialog
進行繪圖?或者,有沒有更好的方法來做到這一點,而不需要在類之間傳遞變量?我的程序是基於this的答案。我應該在類之間傳遞GUI輸入變量還是重構程序?
from PyQt4 import QtCore, QtGui, uic
# Import Qt widgets
from matplotlib.backends.backend_qt4agg \
import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg \
import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
GUI_FILE = "Minimal_UI.ui" # GUI with line edit and 'enter' button
form_class = uic.loadUiType(GUI_FILE)[0]
class MyWidget(QtGui.QWidget, form_class):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.setupUi(self)
self.pushButton_Enter.clicked.connect(self.on_pushButton_clicked)
self.dialogTextBrowser = MyDialog(self)
@QtCore.pyqtSlot()
def on_pushButton_clicked(self):
# I'd like to be able to pass Temp_0 to the run method
self.Temp_0 = self.lineEdit_Temp_0.text()
self.dialogTextBrowser.exec_()
class MyDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
self.fig = Figure()
self.canvas = FigureCanvas(self.fig)
self.toolbar = NavigationToolbar(self.canvas, self)
self.run_button = QtGui.QPushButton('Run')
self.run_button.clicked.connect(self.run)
self.stop_button = QtGui.QPushButton('Stop')
self.stop_button.clicked.connect(self.stop)
layout = QtGui.QVBoxLayout()
# Widgets are stacked in the order they are added
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.run_button)
layout.addWidget(self.stop_button)
self.setLayout(layout)
def run(self):
# Create axes
ax = self.fig.add_subplot(111)
# Discard the old graphs
ax.hold(False)
# Plot data--I'd like to be able to use line edit data here
ax.plot([1, 2, 3, 4], '*-')
# Refresh canvas
self.canvas.draw()
def stop(self):
print 'Stop Pressed'
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWidget')
main = MyWidget()
main.show()
sys.exit(app.exec_())
感謝您的回覆。在運行中使用parent()方法。請澄清你的意思是「使用父屬性還是直接在__init__函數中傳遞數據」,因爲我還沒有能夠得到這個工作,並根據你的建議,這些技術更適合我的應用程序。 – Drew
我我會用'self.dialogTextBrowser = MyDialog(self.lineEdit.text(),self)',用構造函數'__init __(self,data,parent = None)'初始化MyDialog'。這樣,對話框就是專門爲「數據」構建的,沒有它就不能存在。但這實際上只是一種個人偏好,對我來說似乎更合乎邏輯。使用'parent()'也是非常合適的。 – Mel