python - PyQt4:将项目从一个 QListWidget 移动到另一个

标签 python pyqt4 qlistwidget

我在 Qt Designer 上创建了一个界面,并在 QGIS 插件中使用它。该界面由源 listWidget、目标 listWidgetpushButton 组成。

我正在尝试将所选项目从源 listWidget 转移到目标 listWidget

我使用我的源 listWidget 填充:

self.ui.listWidget_1.addItems(soilList)

到目前为止,我已将按钮信号编写为:

QObject.connect(self.ui.pushButton, SIGNAL("clicked()"), self.click_pushButton)

但现在我在编写填充目标 listWidgetclick_pushButton 函数时遇到了麻烦。任何帮助将不胜感激,谢谢!

最佳答案

QListWidget.selectedIndexes() 将返回所选项目的索引列表。其中每个索引都有一个 .row() 方法返回项目的行。然后,您可以使用 .takeItem() 从第一个列表中获取(并删除)该项目,并通过 .addItem() 将其添加到第二个列表。

这意味着:

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.ui.listWidget_1.selectedIndexes()],
                  reverse=True)
    for row in rows:
        # assuming the other listWidget is called listWidget_2
        self.ui.listWidget_2.addItem(self.ui.listWidget_1.takeItem(row))

# moving all items:
def click_pushButton(self):
    for row in reversed(range(self.ui.listWidget_1.count()):
        # assuming the other listWidget is called listWidget_2
        self.ui.listWidget_2.addItem(self.ui.listWidget_1.takeItem(row))

顺便说一句,请为您的小部件/方法指定有意义的名称。 listWidget_1click_pushButton 没有说明它们代表什么。

并使用new style signals and slots 。您可以像这样编写连接语句:

self.ui.pushButton.clicked.connect(self.click_pushButton)

关于python - PyQt4:将项目从一个 QListWidget 移动到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9713298/

相关文章:

python - 按数字对 QListWidget 进行排序

python - 无法在 VS Code 中导入tensorflow.keras

python - postgresql(aws redshift) 错误1204 String length exceeds DDL length

python - 在 QStyledItemDelegate 中显示 QComboBox 文本而不是索引值

python - 使用 raw_input 会导致 PyQt 页面加载出现问题

python - 我想在 QlineEdit onclick 项目中显示 QlistWidgets 项目

python - 使用 seaborn 更改直方图上的轴单位

python - pandas 中的高效扩展 OLS

python - 清除 QListWidget 中的选择

python - 向 QlistView 添加项目