52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
![]() |
from PySide6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget
|
||
|
from PySide6.QtCore import Qt
|
||
|
import sys
|
||
|
|
||
|
class MainWindow(QWidget):
|
||
|
def __init__(self):
|
||
|
super().__init__()
|
||
|
self.setWindowTitle("TreeWidget with Checkboxes")
|
||
|
self.setGeometry(100, 100, 400, 300)
|
||
|
|
||
|
# 创建 QTreeWidget
|
||
|
self.tree = QTreeWidget()
|
||
|
self.tree.setHeaderLabels(["Item", "Description"]) # 设置列标题
|
||
|
|
||
|
# 添加顶层项
|
||
|
root = QTreeWidgetItem(self.tree)
|
||
|
root.setText(0, "Root Item")
|
||
|
root.setText(1, "Root Description")
|
||
|
root.setCheckState(0, Qt.Unchecked) # 设置复选框为未选中
|
||
|
|
||
|
# 添加子项
|
||
|
child1 = QTreeWidgetItem(root)
|
||
|
child1.setText(0, "Child 1")
|
||
|
child1.setText(1, "Child 1 Description")
|
||
|
child1.setCheckState(0, Qt.Checked) # 设置复选框为选中
|
||
|
|
||
|
child2 = QTreeWidgetItem(root)
|
||
|
child2.setText(0, "Child 2")
|
||
|
child2.setCheckState(0, Qt.Unchecked) # 设置复选框为未选中
|
||
|
|
||
|
# 展开顶层项
|
||
|
self.tree.expandAll()
|
||
|
|
||
|
# 布局
|
||
|
layout = QVBoxLayout(self)
|
||
|
layout.addWidget(self.tree)
|
||
|
self.setLayout(layout)
|
||
|
|
||
|
# 监听复选框状态变化
|
||
|
self.tree.itemChanged.connect(self.on_item_changed)
|
||
|
|
||
|
def on_item_changed(self, item, column):
|
||
|
if column == 0: # 检测第一列的复选框状态
|
||
|
state = item.checkState(0)
|
||
|
print(f"Item '{item.text(0)}' checked: {state == Qt.Checked}")
|
||
|
|
||
|
# 主程序
|
||
|
app = QApplication(sys.argv)
|
||
|
window = MainWindow()
|
||
|
window.show()
|
||
|
sys.exit(app.exec())
|