I wrote this small Application using pyqt5: from the menubar of the MainWindow I can choose a folder and I would like to pass the path of the choosen folder to the QLineEdit "txtPath" which is in the other class named "YtDownloader". I stuck in this issue since "txtPath" is unknown from the MainWindow.
import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
class YtDownloader(qtw.QWidget):
def __init__(self):
super().__init__()
self.setLayout(qtw.QFormLayout())
self.txtPath = qtw.QLineEdit(placeholderText='Select the download path from the menu')
self.layout().addRow(self.txtPath)
class MainWindow(qtw.QMainWindow):
def __init__(self):
super().__init__()
# Main UI code goes here
# Menubar
menubar = self.menuBar()
file_menu = menubar.addMenu('File')
file_menu.addAction('Select Download Folder', self.getDownloadFolder)
# Central Widget
self.lstStream = qtw.QListWidget()
self.setCentralWidget(self.lstStream)
# Dockable Widget
ytd_dock = qtw.QDockWidget('Dock Panel')
self.addDockWidget(qtc.Qt.RightDockWidgetArea, ytd_dock)
ytd_dock.setFeatures(qtw.QDockWidget.DockWidgetMovable | qtw.QDockWidget.DockWidgetFloatable)
ytd_widget = YtDownloader()
ytd_dock.setWidget(ytd_widget)
# End main UI code
self.show()
def getDownloadFolder(self):
try:
self.dirname = qtw.QFileDialog.getExistingDirectory()
if self.dirname:
# self.txtPath.setText(self.dirname) --> this does not work
qtw.QMessageBox.information(self, '', self.dirname)
except Exception as e:
qtw.QMessageBox.critical(self, 'Error', str(e))
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
# it's required to save a reference to MainWindow.
# if it goes out of scope, it will be destroyed.
mw = MainWindow()
sys.exit(app.exec())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…