如何在Python中为QListWidget设置ContiguousSelection选择模式
解决PyQt6中QListWidget设置ContiguousSelection选择模式的问题
问题根源
PyQt6对Qt的枚举类型做了规范化重构,所有枚举成员都被归类到对应的枚举子类中。ContiguousSelection属于QAbstractItemView.SelectionMode枚举类,不再直接作为QAbstractItemView的顶层属性存在。
错误分析
QAbstractItemView:ContiguousSelection是Qt C++的语法,Python不支持用冒号访问枚举,因此触发语法错误。QAbstractItemView.ContiguousSelection是PyQt5的写法,PyQt6重构枚举结构后,该路径已失效,所以提示找不到属性。
正确写法
有两种可行方式设置连续选择模式:
- 使用完整枚举路径:
self.widget.setSelectionMode(QAbstractItemView.SelectionMode.ContiguousSelection)
- 单独导入枚举类简化代码:
from PyQt6.QtWidgets import SelectionMode self.widget.setSelectionMode(SelectionMode.ContiguousSelection)
修改后的完整可运行代码
import sys from PyQt6.QtWidgets import ( QApplication, QMainWindow, QListWidget, QAbstractItemView ) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("My App") self.widget = QListWidget() self.setCentralWidget(self.widget) self.widget.addItems(["One", "Two", "Three", "Four", "Five", "Six"]) self.widget.currentItemChanged.connect(self.index_changed) # 正确设置连续选择模式 self.widget.setSelectionMode(QAbstractItemView.SelectionMode.ContiguousSelection) print('-='*35, end='\n\n') print("已设置为连续选择模式,可按住鼠标拖动或按住Shift键选择连续项".center(80)) def index_changed(self, i): print(i.text()) app = QApplication(sys.argv) window = MainWindow() window.show() app.exec()
效果验证
运行代码后,可通过两种方式选择连续项:
- 按住鼠标左键拖动,直接选中连续的多个列表项
- 选中单个项后,按住Shift键点击另一项,选中两项之间的所有连续内容
内容的提问来源于stack exchange,提问作者user10637953
相关产品推荐
相关产品推荐

