I think I understand Python classes, but obviously I do not (Newbie in Python).
I have a class MainWindow(QWidget) and I want to use the outcome if the file selection dialog in the main program or somewhere else. That means, I want to get (export) the variable filenames in open_file_dialog(self)-
Maybe the code example shows my problem more clearly.
import sys
from PyQt6.QtWidgets import (
QApplication,
QWidget,
QFileDialog,
QGridLayout,
QPushButton,
QLabel,
QListWidget
)
from pathlib import Path
class MainWindow(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('PyQt File Dialog')
self.setGeometry(100, 100, 300, 150)
layout = QGridLayout()
self.setLayout(layout)
# file selection
file_browser_btn = QPushButton('Browse')
file_browser_btn.clicked.connect(self.open_file_dialog)
self.file_list = QListWidget(self)
layout.addWidget(QLabel('Files:'), 0, 0)
layout.addWidget(self.file_list, 1, 0)
layout.addWidget(file_browser_btn, 2 ,0)
self.show()
def open_file_dialog(self):
dialog = QFileDialog(self)
dialog.setDirectory(r'C:')
dialog.setFileMode(QFileDialog.FileMode.ExistingFiles)
dialog.setNameFilter("Text (*.txt *.eml)")
dialog.setViewMode(QFileDialog.ViewMode.List)
if dialog.exec():
self.lw = QWidget.QListWidget()
filenames = dialog.selectedFiles()
if filenames:
self.file_list.addItems([str(Path(filename)) for filename in filenames])
# y=self.file_list
# super().y=self.file_list
# MainWindow.y=self.file_list
# MainWindow.y=filenames
QWidget.QListWidgetItem('myItem only 1', self.lw)
x=1
# y=self.file_list
# y=filenames
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
# fnames = QStringList()
# print (window.__getattribute__ ('file_list'))
# print (window::file_list())
# print (window.dialog.selectedfiles ())
# print (window.selectedfiles())
# print (window.filenames)
# print (window.file_list [1])
# print (window.y [1])
# print (window.y)
# lst = QWidget.file_list()
# lst = QWidget.lw()
# lst = QWidget.QListWidget()
lst = window.QListWidget()
items = []
for x in range(lst.count()):
items.append(lst.item(x).text())
print(items)
# I want the list of selected files here, nothng works ...
sys.exit(app.exec())