2 QListWidget之间如何交换多少项目?
Posted
技术标签:
【中文标题】2 QListWidget之间如何交换多少项目?【英文标题】:How exchange many items between 2 QListWidget? 【发布时间】:2017-06-12 15:20:15 【问题描述】:我有一个新问题要问你。我有 2 个带有许多项目的 QListWidget。我想选择许多项目,单击一个按钮,然后在第二个 QListWidget 中剪切/粘贴,反之亦然。
有人知道我该怎么做???
这是我发展的开始:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(816, 603)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget1 = QtWidgets.QListWidget(MainWindow)
self.listWidget1.setGeometry(QtCore.QRect(370, 120, 151, 311))
self.listWidget1.setObjectName("listWidget1")
self.listWidget1.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
item = QtWidgets.QListWidgetItem()
self.listWidget1.addItem(item)
item = QtWidgets.QListWidgetItem()
self.listWidget1.addItem(item)
self.listWidget_2 = QtWidgets.QListWidget(MainWindow)
self.listWidget_2.setGeometry(QtCore.QRect(600, 120, 151, 311))
self.listWidget_2.setObjectName("listWidget_2")
self.listWidget_2.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
self.pushButton_3 = QtWidgets.QPushButton(MainWindow)
self.pushButton_3.setGeometry(QtCore.QRect(540, 220, 51, 21))
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(MainWindow)
self.pushButton_4.setGeometry(QtCore.QRect(540, 270, 51, 21))
self.pushButton_4.setObjectName("pushButton_4")
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
__sortingEnabled = self.listWidget1.isSortingEnabled()
self.listWidget1.setSortingEnabled(False)
item = self.listWidget1.item(0)
item.setText(_translate("MainWindow", "test1"))
item = self.listWidget1.item(1)
item.setText(_translate("MainWindow", "test2"))
self.listWidget1.setSortingEnabled(__sortingEnabled)
self.pushButton_3.setText(_translate("MainWindow", "-->"))
self.pushButton_4.setText(_translate("MainWindow", "<--"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
【问题讨论】:
【参考方案1】:我只是找到了答案。如果有一天有人遇到同样的问题,我会把结果放在这里。
当我单击按钮并使用 3 个函数时,我创建了一个新函数: - 选定索引 - takeItem(从第一个 QListWidget 中删除) - addItem(在第二个QListWidget中添加项目)
def click_pushButton(self):
# sort rows in descending order in order to compensate shifting due to takeItem
rows = sorted([index.row() for index in self.listWidget1.selectedIndexes()],
reverse=True)
print('AAA')
for row in rows:
# assuming the other listWidget is called listWidget_2
self.listWidget_2.addItem(self.listWidget1.takeItem(row))
【讨论】:
以上是关于2 QListWidget之间如何交换多少项目?的主要内容,如果未能解决你的问题,请参考以下文章
在PyQt5中的QTreeWidget和QListWidget之间拖动项目?