我正在使用PyQt6和SQlite3开发数据库软件。我在组织文件和类方面有点困难,因为这是我的第一个此类项目。我将 main.py 保留在根目录中以打开窗口,并且我有各种堆叠的小部件,如 home_page、dashboard_page 等。每个这样的页面都有各种 QWidget(按钮、组合框等)。为了分离控制器文件夹内的任务,我为每个堆叠页面提供了文件,这些文件定义了相应页面中每个小部件的任务。所以我有以下目录:
root_directory/
│
├── main.py
│
├── ui/
│ ├── ui_main.py
│ └── ui_functions.py
│
└── controller/
├── home_page_controller.py
└── (other_controller_files.py)
在主文件中,我创建了一个 MainWindow 类,它是 QMainWindow 的实例,并初始化了 UI 组件:
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# SET AS GLOBAL WIDGETS
# ///////////////////////////////////////////////////////////////
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
global widgets
widgets = self.ui
然后我尝试在 homepage_controller.py 中创建 HomePageController 类。这是代码:
from PyQt6.QtWidgets import QFileDialog
class HomePageController:
def __init__(self, Ui_MainWindow):
self.ui = Ui_MainWindow
# Connect buttons to functions
self.ui.open_db_btn_homepage.clicked.connect(self.open_db)
self.ui.create_new_db_btn_homepage.clicked.connect(self.create_new_db)
def open_db(self):
file_name, _ = QFileDialog.getOpenFileName(self.ui, "Open database file", "", "All Files (*)")
if file_name:
print(file_name)
但是这样我就无法从 HomePageCotroller 类访问任何小部件。结果我从 QFileDialog 收到错误:
Traceback (most recent call last):
File "d:\Python_workspace\app\controller\home_page_controller.py", line 14, in open_db
file_name, _ = QFileDialog.getOpenFileName(self.ui, "Open database file", "", "All Files (*)")
TypeError: getOpenFileName(parent: typing.Optional[QWidget] = None, caption: str = '', directory: str = '', filter: str = '', initialFilter: str = '', options: QFileDialog.Option = QFileDialog.Options()): argument 1 has unexpected type 'Ui_MainWindow'
为了解决这个问题,我在 MainWindow 类中尝试了以下行:
# Instantiate HomePageController with self as the parent widget
self.home_page_controller = HomePageController(self.ui)
我能够通过以下方式解决问题,但不确定这是否是最有效的方法。
class HomePageController(QWidget):
def __init__(self, MainWindow):
super().__init__()
self.main_window = MainWindow.ui
# Connect buttons to functions
self.main_window.open_db_btn_homepage.clicked.connect(self.open_db)
self.main_window.create_new_db_btn_homepage.clicked.connect(self.create_new_db)