I do not know of a way to "suspend" tree updates, but what about using lists to store the children until one decides to update? See the modified example below (modifications are commented):
import sys
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QApplication, QMainWindow, QToolBar, QAction, QTreeWidget, QTreeWidgetItem
class Table(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.resize(800, 600)
self.setMinimumSize(QSize(800, 600))
self.table = QTreeWidget()
self.table.setHeaderLabels(["Description", "Price"])
self.setCentralWidget(self.table)
self.car = QTreeWidgetItem(["Car"])
self.house = QTreeWidgetItem(["House"])
self.table.addTopLevelItem(self.car)
self.table.addTopLevelItem(self.house)
# initialize empty lists which will keep track of generated children
self.car_list, self.house_list = [], []
toolbar = QToolBar("Toolbar")
carAction = QAction("Car", self)
carAction.triggered.connect(self.addToCar)
houseAction = QAction("House", self)
houseAction.triggered.connect(self.addToHouse)
updateAction = QAction("Update", self)
updateAction.triggered.connect(self.update)
toolbar.addAction(carAction)
toolbar.addAction(houseAction)
toolbar.addAction(updateAction)
self.addToolBar(toolbar)
def addToCar(self):
child = QTreeWidgetItem(["Audi", str(25000)])
# instead of adding them directly to the tree, keep them in the list
self.car_list.append(child)
def addToHouse(self):
child = QTreeWidgetItem(["Villa", str(500000)])
# instead of adding them directly to the tree, keep them in the list
self.house.addChild(child)
def update(self):
# update the tree and reset the lists
self.car.addChildren(self.car_list)
self.house.addChildren(self.house_list)
self.car_list, self.house_list = [], []
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Table()
win.show()
sys.exit( app.exec_() )
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…