我有一个自定义的ListWidgetItem类SubItem
,它继承自通常的QListWidgetItem。当我在两个ListWidgets之间拖放项目时,我丢失了不属于QListWidgetItem的所有内容。下面是一个示例。请注意,所有项目最初都列为SubItem
类型。我们可以访问常见的ListWidgetItem属性,例如setBackground()
以及SubItem
中定义的新属性,例如name
。将项目拖动到listWidget2后,它会保留其背景,但不再具有对name属性的访问权限。注释掉name属性,printTypes()
函数确认该项目现在是QListWidgetItem而不是SubClass项目。
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
class SubItem(QtWidgets.QListWidgetItem):
def __init__(self, name):
super(SubItem, self).__init__(name)
self.setBackground(QtGui.QColor('#A3B5C7'))
self.name = name
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.widget = QtWidgets.QWidget()
self.widget.setLayout(QtWidgets.QVBoxLayout())
self.setCentralWidget(self.widget)
self.listWidget1 = QtWidgets.QListWidget()
self.listWidget1.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.listWidget1.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.listWidget1.setDefaultDropAction(QtCore.Qt.MoveAction)
self.listWidget1.setAcceptDrops(True)
self.widget.layout().addWidget(self.listWidget1)
for n in ['a', 'b', 'c']:
self.listWidget1.addItem(SubItem(n))
self.listWidget2 = QtWidgets.QListWidget()
self.listWidget2.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.listWidget2.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.listWidget2.setDefaultDropAction(QtCore.Qt.MoveAction)
self.listWidget2.setAcceptDrops(True)
self.widget.layout().addWidget(self.listWidget2)
self.button = QtWidgets.QPushButton('Show Types')
self.widget.layout().addWidget(self.button)
self.button.clicked.connect(self.printTypes)
self.show()
def printTypes(self):
count = self.listWidget1.count()
for i in range(count):
item = self.listWidget1.item(i)
print('Widget1: ', item.name, item)
count = self.listWidget2.count()
for i in range(count):
item = self.listWidget2.item(i)
print('Widget2: ', item.name, item)
app = QtWidgets.QApplication(sys.argv)
m = MainWindow()
sys.exit(app.exec_())
我是否需要以某种方式重载dropEvent()
?如何确保将整个类传递给新的ListWidget?