我正在使用Python3.6和PySide2
我有一个treewidget-A,里面有员工列表。
在雇员(treewidget-A项目)上单击时,将填充另一个treeWidget-B。
现在,如果我单击空白区域(取消选择项目),但是treeWidget-B仍显示上次单击的员工项目详细信息。
这是为了填充treewidget项目
self.treeWidget_A.itemClicked.connect(self.populate_employee)
self.treeWidget_A.currentItemChanged.connect(self.populate_employee)
单击QtreeWidget的空白区域时如何执行clear_employee_data()函数?
def clear_employee_data(self):
self.treeWidget_B.clear()
最佳答案
您必须检测点击并确认没有任何项目:
from PySide2 import QtCore, QtWidgets
class TreeWidget(QtWidgets.QTreeWidget):
emptyClicked = QtCore.Signal()
def __init__(self, parent=None):
super(TreeWidget, self).__init__(parent)
for i in range(2):
it = QtWidgets.QTreeWidgetItem(self, ["item-{}".format(i)])
for j in range(3):
child_it = QtWidgets.QTreeWidgetItem(it, ["item-{}-{}".format(i, j)])
self.expandAll()
def mousePressEvent(self, event):
super(TreeWidget, self).mousePressEvent(event)
if not self.indexAt(event.pos()).isValid():
self.emptyClicked.emit()
@QtCore.Slot()
def on_empty_clicked():
print("clicked")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = TreeWidget()
w.emptyClicked.connect(on_empty_clicked)
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
与Qt Designer一起使用eventfilter:
from PySide2 import QtCore, QtGui, QtWidgets
from design import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
emptyClicked = QtCore.Signal()
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.treeWidget_A.viewport().installEventFilter(self)
self.emptyClicked.connect(self.on_emptyClicked)
def eventFilter(self, obj, event):
if obj is self.treeWidget_A.viewport() and event.type() == QtCore.QEvent.MouseButtonPress:
if not self.treeWidget_A.indexAt(event.pos()).isValid():
self.emptyClicked.emit()
return super(MainWindow, self).eventFilter(obj, event)
@QtCore.Slot()
def on_emptyClicked(self):
print("empty")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())