from PySide6.QtWidgets import QApplication, QListWidget, QMainWindow
def text_changed(i: str):
print('text changed to: {}'.format(i))
class MyListWidget(QMainWindow):
def __init__(self):
super().__init__()
my_list = QListWidget()
my_list.addItems(['a', 'b', 'c', 'd', 'e'])
my_list.currentTextChanged.connect(text_changed)
print('default selection mode:', my_list.selectionMode())
self.setCentralWidget(my_list)
if __name__ == '__main__':
app = QApplication()
ins = MyListWidget()
ins.show()
app.exec()
from PySide6.QtCore import QItemSelection
from PySide6.QtWidgets import QApplication, QComboBox, QListWidget, QMainWindow, QVBoxLayout, QWidget
selectionMap = {
'SingleSelection': QListWidget.SelectionMode.SingleSelection,
'NoSelection': QListWidget.SelectionMode.NoSelection,
'ExtendedSelection': QListWidget.SelectionMode.ExtendedSelection,
'ContiguousSelection': QListWidget.SelectionMode.ContiguousSelection,
'MultiSelection': QListWidget.SelectionMode.MultiSelection,
}
class ListWidgetSelectionModes(QMainWindow):
def __init__(self):
super().__init__()
my_combobox = QComboBox()
my_combobox.addItems(list(selectionMap.keys()))
my_combobox.setWindowTitle('ListWidget Selection Modes')
my_combobox.setEditable(False)
my_combobox.setMaxVisibleItems(len(list(selectionMap.keys())))
my_combobox.setMaxCount(len(list(selectionMap.keys())))
my_combobox.setDuplicatesEnabled(False)
my_combobox.currentTextChanged.connect(self.change_list_selection_mode)
self.my_list_widget = QListWidget()
self.my_list_widget.addItems([chr(x) for x in range(ord('a'), ord('z') + 1)])
self.my_list_widget.selectionModel().selectionChanged.connect(self.list_selection_changed)
my_v_layout = QVBoxLayout()
my_v_layout.addWidget(my_combobox)
my_v_layout.addWidget(self.my_list_widget)
container = QWidget()
container.setLayout(my_v_layout)
self.setCentralWidget(container)
def change_list_selection_mode(self, selection_mode: str):
self.my_list_widget.setSelectionMode(selectionMap[selection_mode])
print('change selection mode to: {}'.format(selection_mode))
def list_selection_changed(self, selected: QItemSelection, deselected: QItemSelection):
selected_indexes = [index.row() for index in selected.indexes()]
deselected_indexes = [index.row() for index in deselected.indexes()]
print("Selected Items indexes:", selected_indexes,
'Items data:', [x.text() for x in self.my_list_widget.selectedItems()],
"Deselected items:", deselected_indexes)
if __name__ == '__main__':
app = QApplication()
ins = ListWidgetSelectionModes()
ins.show()
app.exec()
这种模式只允许选择单个项目。
这种模式只允许用户选择一个连续的项目块。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。