class MyMainWindow(QMainWindow):
def __init__(self, parent=None):
# omitted
def _generate_ui(self):
main_widget = QWidget()
main_layout = QVBoxLayout()
main_widget.setLayout(main_layout)
self.setCentralWidget(main_widget)
self.tree_widget = QTreeWidget()
self.tree_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.tree_widget.setSelectionBehavior(QAbstractItemView.SelectItems)
self.tree_widget.itemDoubleClicked.connect(self._doubleClicked) # connect function to the signal itemDoubleClicked
main_layout.addWidget(self.tree_widget)
def _init_tree_widget(self):
# omitted
def _doubleClicked(self): # this function is executed when an item is double clicked
print("double clicked")
I’d like to clear and redraw widgets in my custom PySide2 UI.
GOAL
Today’s goal is to remove and delete all children widgets from the layout.
Environment
Windows 10 Python 3.8.7 PySide2 (5.15.2)
Method
I created sample widget with clear-all button.
import sys
from PySide2.QtWidgets import *
from PySide2.QtCore import Qt, QEventLoop
class MyWidget(QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.main_layout = QVBoxLayout()
self.setLayout(self.main_layout)
self._generateUI()
def _generateUI(self):
clear_button = QPushButton("Clear All")
clear_button.clicked.connect(self._clearall)
self.main_layout.addWidget(clear_button)
label = QLabel("Label")
self.main_layout.addWidget(label)
combobox = QComboBox()
combobox.addItems(["comboBox1", "comboBox2"])
self.main_layout.addWidget(combobox)
buttons_widget = QWidget()
buttons_layout = QHBoxLayout()
buttons_widget.setLayout(buttons_layout)
for i in range(3):
button = QPushButton("button"+str(i))
buttons_layout.addWidget(button)
self.main_layout.addWidget(buttons_widget)
def _clearall(self): # the function to clear widgets
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
1. Get all children
To get the list of children in the layout, use count() and itemAt(). Because the itemAt() function returns QLayoutItem not Qwidget, we should get widget by using QLayoutItem.widget() method.
def _clearall(self):
children = []
for i in range(self.main_layout.count()):
child = self.main_layout.itemAt(i).widget()
if child:
children.append(child)
print(child)
# output
# <class 'PySide2.QtWidgets.QPushButton'>
# <class 'PySide2.QtWidgets.QLabel'>
# <class 'PySide2.QtWidgets.QComboBox'>
# <class 'PySide2.QtWidgets.QWidget'>
def _clearall(self):
children = []
for i in range(self.main_layout.count()):
child = self.main_layout.itemAt(i).widget()
if child:
children.append(child)
for child in children:
child.deleteLater()
* There are many ways to remove widget from the parent layout. For example, some people use setParent(None) or something. However don’t use removeWidget() because it just removes widget without destroying it. Please refer to the discussion below.
There are another methods to implement _clearall() function.
The method in which items deleted in for loop
It works well because the deleteLater() destroys items after returning control from the function.
def _clearall(self):
for i in range(self.main_layout.count()):
child = self.main_layout.itemAt(i).widget()
child.widget().deleteLater()
This is a wrong example. The itemAt() function can’t find the child because when an item is deleted with setParent(None), other items will be renumbered.
def _clearall(self): #wrong example
for i in range(self.main_layout.count()):
child = self.main_layout.itemAt(i).widget()
child.setParent(None)
# An error occurred: AttributeError: 'NoneType' object has no attribute 'widget'
f = open('test.txt', 'r')
# getting class name
print(f.__class__.__name__)
#output => TextIOWrapper
# getting the module where the class is defined
print(f.__class__.__module__)
#output => _io
f.close()
def import_n_th_module(index):
"""
the function to get index number and import the module named mymodule+index such as mymodule1, mymodule2,...
"""
module_name = 'mymodule' + str(index)
# import module_name => the error occured
The purpose of the importlib package is two-fold. One is to provide the implementation of the import statement (and thus, by extension, the import() function) in Python source code. <omit>
I created 3 modules in modules package. And each module prints “[module_name] is imported” when being imported.
#test.py
import sys
import importlib
index = 3
importlib.import_module('modules.mymodule' + str(index))
# output => "mymodule3 is imported"
Postscript
Another purpose of the imporlib
Two, the components to implement import are exposed in this package, making it easier for users to create their own custom objects (known generically as an importer) to participate in the import process.
def get_keyconfigs():
"""
:return: dict{kerconfig_name(str): path to config file(str)}
"""
config_pathes = bpy.utils.preset_paths("keyconfig")
config_dict = {}
for config_path in config_pathes:
for file in os.listdir(config_path):
name, ext = os.path.splitext(file)
if ext.lower() in [".py", ".xml"] and not name[0] == ".":
config_dict[name] = os.path.join(config_path, file)
return config_dict
2.2 Activate specified keyconfig and return active keyconfig
Activate the specified keyconfig by its path and get active keyconfig with wm.keyconfigs.active then restore active keyconfig to original settings.
def get_keyconfig(keyconfig_name, keyconfig_dict):
wm = bpy.context.window_manager
if keyconfig_name in wm.keyconfigs.keys(): #if the keyconfig can be found, return it
return wm.keyconfigs[keyconfig_name]
else: # activate by config path and return it
keyconfig_path = keyconfig_dict[keyconfig_name]
current_path = keyconfig_dict[wm.keyconfigs.active.name]
bpy.ops.preferences.keyconfig_activate(filepath=keyconfig_path)
kc = wm.keyconfigs.active
bpy.ops.preferences.keyconfig_activate(filepath=current_path)
return kc
class ItemWidget(QWidget):
def __init__(self, id_str="", parent=None):
super(ItemWidget, self).__init__(parent)
self.id_str = id_str
self._generateUI()
def _generateUI(self):
main_layout = QGridLayout()
self.setLayout(main_layout)
title = QLabel("title" + self.id_str)
main_layout.addWidget(title, 0, 0, 1, 3)
close_button = QPushButton("-")
close_button.setFixedWidth(30)
close_button.clicked.connect(self._close_widget) # add to close the widget
main_layout.addWidget(close_button, 0, 3, 1, 1)
spinbox = QSpinBox()
main_layout.addWidget(spinbox, 1, 0, 1, 4)
def _close_widget(self):
self.deleteLater() # main function to close widget
* There are many ways to remove widget from the parent layout. For example, some people use setParent(None) or something. However don’t use removeWidget() because it just removes widget without destroying it. Please refer to the discussion below.
I don’t know why but adjustSize() doesn’t work correctly until some events are processed in the event loop. So I called QApplication.processEvents() in the for loop. Please let me know if you have any idea about this