在 PyQt 中實現在多個標簽頁中復用同一個 QTableView
實例,復用同一個 QTableView
實例可以減少內存和資源的使用。每個 QTableView
實例都會消耗一定的內存和處理資源,如果每個標簽頁都創建一個新的實例,會增加系統的負擔。通過復用實例,可以顯著降低資源消耗,提升應用程序的性能。
1、問題背景
在使用 PyQt5 開發 GUI 程序時,有時需要在多個標簽頁中顯示相同的數據。為了提高性能,希望使用同一個 QTableView 來顯示不同標簽頁中的數據,只需過濾數據即可。
2、解決方案
經過調研,發現 QTableView 不支持在多個標簽頁中復用。最優雅的解決方案是為每個標簽頁創建一個獨立的 QTableView。
代碼例子1:創建獨立的 QTableView
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QTableView, QVBoxLayout, QPushButtonclass MainWindow(QMainWindow):def __init__(self):super().__init__()self.setWindowTitle("Multiple TableViews in Tabs")self.resize(640, 480)# Create a QTabWidget to hold the tabsself.tabs = QTabWidget()# Create a QTableView for each tabself.tableView1 = QTableView()self.tableView2 = QTableView()# Add the table views to the tabsself.tabs.addTab(self.tableView1, "Tab 1")self.tabs.addTab(self.tableView2, "Tab 2")# Set the central widget to the tab widgetself.setCentralWidget(self.tabs)if __name__ == "__main__":app = QApplication(sys.argv)window = MainWindow()window.show()sys.exit(app.exec_())
代碼例子2:使用同一個 QTableView 過濾數據
由于 QTableView 不支持在多個標簽頁中復用,因此如果需要在多個標簽頁中顯示相同的數據,但需要過濾數據,可以使用以下方法:
- 創建一個 QAbstractItemModel,該模型包含所有數據。
- 為每個標簽頁創建 QTableView,并使用相同的 QAbstractItemModel。
- 為每個 QTableView 設置不同的數據過濾器,以便只顯示所需的數據。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QTableView, QVBoxLayout, QPushButton, QSortFilterProxyModelclass MainWindow(QMainWindow):def __init__(self):super().__init__()self.setWindowTitle("Multiple TableViews with Filtered Data")self.resize(640, 480)# Create a QTabWidget to hold the tabsself.tabs = QTabWidget()# Create a QAbstractItemModel to hold the dataself.model = QAbstractItemModel()# Create QTableViews for each tabself.tableView1 = QTableView()self.tableView2 = QTableView()# Create QSortFilterProxyModels for each table viewself.proxyModel1 = QSortFilterProxyModel()self.proxyModel2 = QSortFilterProxyModel()# Set the source model for the proxy modelsself.proxyModel1.setSourceModel(self.model)self.proxyModel2.setSourceModel(self.model)# Set the proxy models for the table viewsself.tableView1.setModel(self.proxyModel1)self.tableView2.setModel(self.proxyModel2)# Set the filters for the proxy modelsself.proxyModel1.setFilterKeyColumn(0)self.proxyModel1.setFilterFixedString("Tab 1")self.proxyModel2.setFilterKeyColumn(0)self.proxyModel2.setFilterFixedString("Tab 2")# Add the table views to the tabsself.tabs.addTab(self.tableView1, "Tab 1")self.tabs.addTab(self.tableView2, "Tab 2")# Set the central widget to the tab widgetself.setCentralWidget(self.tabs)if __name__ == "__main__":app = QApplication(sys.argv)window = MainWindow()window.show()sys.exit(app.exec_())
通過這種方法,你可以在 PyQt 應用程序中輕松地在多個標簽頁中復用同一個 QTableView
實例,并根據需要對每個標簽頁的視圖進行自定義配置和操作。