I am learning Pyqt5, but I can`t understand completely how to use signal and slot.
from PySide2.QtWidgets import QApplication, QTreeWidgetItem,QTreeWidget
from PySide2.QtCore import Qt
dat = { 'A':
{ 'A':
{'1.1': ['1.1.1', '1.1.2'],
'1.2': ['1.2.1', '1.2.2']
},
'2':
{'2.1': ['2.1.1','2.1.2']}
}
}
def add(p,ch):
if isinstance(ch,dict):
for k,v in ch.items():
item = QTreeWidgetItem(p)
item.setText(0, k)
item.setCheckState(0, Qt.Unchecked)
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
add(item,v)
else:
for txt in ch:
item = QTreeWidgetItem(p)
item.setText(0, txt)
item.setCheckState(0, Qt.Unchecked)
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
app = QApplication([])
tw = QTreeWidget()
add(tw,dat)
app.show()
app.exec_()
I want to check the checkbox and return which node I selected but I don't know how to get the signal. I find that QTreeWidget has some signal func but i don't know how to use it. thank you for your help.
You can connect the QTreeWidget.itemChanged
signal to get the QTreeWidgetItem that was checked (or unchecked). I edited your code into a viewable GUI. This example will just print the text of the QTreeWidgetItem emitted by the signal.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Template(QWidget):
def __init__(self):
super().__init__()
dat = { 'A':
{ 'A':
{'1.1': ['1.1.1', '1.1.2'],
'1.2': ['1.2.1', '1.2.2']
},
'2':
{'2.1': ['2.1.1','2.1.2']}
}
}
tw = QTreeWidget()
tw.itemChanged[QTreeWidgetItem, int].connect(self.get_item)
grid = QGridLayout(self)
grid.addWidget(tw)
self.add(tw, dat)
def get_item(self, item, column):
if item.checkState(column) == Qt.Checked:
print(f'{item.text(column)} was checked')
else:
print(f'{item.text(column)} was unchecked')
def new_item(self, text):
item = QTreeWidgetItem()
item.setText(0, text)
item.setCheckState(0, Qt.Unchecked)
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
return item
def add(self, p, ch):
for k, v in ch.items():
item = self.new_item(k)
if isinstance(p, QTreeWidget):
p.addTopLevelItem(item)
else:
p.addChild(item)
if isinstance(v, dict):
self.add(item, v)
elif isinstance(v, list):
for txt in v:
item.addChild(self.new_item(txt))
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = Template()
gui.show()
sys.exit(app.exec_())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.