Reputation: 41
I created an interface on Qt Designer and am using it in a QGIS plugin. The interface consists of a source listWidget
, a destination listWidget
, and pushButton
.
I am trying to bring selected items over from the source listWidget
to the destination listWidget
.
I populated by my source listWidget
using:
self.ui.listWidget_1.addItems(soilList)
And so far I have written my button signal as:
QObject.connect(self.ui.pushButton, SIGNAL("clicked()"), self.click_pushButton)
But now I am having trouble writing the click_pushButton
function that populates the destination listWidget
. Any help would be appreciated, thanks!
Upvotes: 2
Views: 3260
Reputation: 11
A QListwidgetitem can only exist in one QListwidget unless cloned.
Here is a straightforward PyQt5 solution which avoids the bookkeeping of indices:
self.ui.clone_items_button.clicked.connect(self.clone_selected_listwidgetitems)
def clone_selected_listwidgetitems(self)
for sel_item in self.ui.source_listwidget.selectedItems():
cloned_item = sel_item.clone()
self.ui.destination_listwidget.addItem(cloned_item)
Upvotes: 1
Reputation: 36715
QListWidget.selectedIndexes()
will return a list of indexes for selected items. Where each index has a .row()
method returning the row of the item. Then you can use .takeItem()
to get (and remove) the item from the first list, and add it to the second list via .addItem()
.
That translates to:
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))
By the way, please give your widgets/methods meaningful names. listWidget_1
or click_pushButton
says nothing about what these stand for.
And use new style signals and slots. You can write that connect statement like this:
self.ui.pushButton.clicked.connect(self.click_pushButton)
Upvotes: 2