将项目从 QTreeWidget 移动到 QListWidget
Posted
技术标签:
【中文标题】将项目从 QTreeWidget 移动到 QListWidget【英文标题】:Moving items from QTreeWidget to QListWidget 【发布时间】:2021-09-12 11:48:41 【问题描述】:当用户按下“确定”按钮时,我试图将选中的项目移动到空列表中。 但我得到这个错误:
Traceback (most recent call last): File "Desktop/abstract.py", line 42, in okButtonSlot
self.listWidget.addItem(item) TypeError: arguments did not match any overloaded call: addItem(self, QListWidgetItem): argument 1 has unexpected type 'QTreeWidgetItem' addItem(self, str): argument 1 has unexpected type 'QTreeWidgetItem'
程序如下所示:
这是代码:
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QHBoxLayout, QListWidget, QPushButton,
QTreeWidgetItem, QWidget, QTreeWidget
parameterList = ["Suction", "Discharge", "Oil", "Motor", "Capacity"]
class TreeTilList(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QHBoxLayout()
self.treeWidget = QTreeWidget()
self.treeWidget.setHeaderLabel("Parameter")
self.listWidget = QListWidget()
self.okButton = QPushButton("Ok")
self.okButton.clicked.connect(self.okButtonSlot)
self.parameter = QTreeWidgetItem(self.treeWidget, ["Control values"])
self.items = list()
for i in parameterList:
item = QTreeWidgetItem(self.parameter, [i])
item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
item.setCheckState(0, QtCore.Qt.Unchecked)
self.items.append(item)
layout.addWidget(self.treeWidget)
layout.addWidget(self.listWidget)
layout.addWidget(self.okButton)
self.setLayout(layout)
def okButtonSlot(self):
for item in self.items:
if item.checkState(0) == QtCore.Qt.Checked:
self.listWidget.addItem(item)
else:
print(item.checkState(0))
def window():
app = QtWidgets.QApplication(sys.argv)
win = TreeTilList()
win.show()
sys.exit(app.exec())
window()
【问题讨论】:
当我这样做时:self.listWidget.addItem(str(item),它会将项目添加到列表中,但项目的对象地址而不是它们的值 【参考方案1】:报错说明QTreeWidgetItem和QListWidgetItem不一样,所以必须从第一个获取信息,复制到第二个:
def okButtonSlot(self):
for item in self.items:
if item.checkState(0) == QtCore.Qt.Checked:
list_item = QListWidgetItem(item.text(0))
self.listWidget.addItem(list_item)
【讨论】:
以上是关于将项目从 QTreeWidget 移动到 QListWidget的主要内容,如果未能解决你的问题,请参考以下文章
如何将qtreewidget的currentindex向上移动一位