Remove item from QListView\QListWidget by string name - python

In PyQt4, How do I delete an item from the QListView\QListWidget by a name string?
def deleteItem(itemName):
item = dialog.listWidget.indexFromItem(itemName)
dialog.listWidget.takeItem(item)
This is what I've got so far, and obviously feeding string to indexFromItem is not working...

First, look for the item in listWidget using findItems:
items_list = dialog.listWidget.findItems(itemName,Qt.MatchExactly)
This will return a list of matched QListWidgetItem with itemName (which should be a list of one item if there is only one item with itemName)
Second, call dialog.listWidget.row() to find row number of your found item(s).
Finally, detele that/those item(s) using dialog.listWidget.takeItem()
So at the end you function would look like this:
def deleteItem(itemName):
items_list = dialog.listWidget.findItems(itemName,QtCore.Qt.MatchExactly)
for item in items_list:
r = dialog.listWidget.row(item)
dialog.listWidget.takeItem(r)
Again, you have to make sure there are no items with same names otherwise they would be deleted all together.

Related

How to move multiple lines at once up or down in PyQt List Widget?

I am using the following code to move a single item up in the PyQt6 list widget
def move_item_up_in_list_box(self):
row = self.listWidget.currentRow()
text = self.listWidget.currentItem().text()
self.listWidget.insertItem(row-1, text)
self.listWidget.takeItem(row+1)
self.listWidget.setCurrentRow(row-1)
But I couldn't find an option to get the index positions when multiple lines are selected, though
'self.listWidget.selectedItems()' returns the texts in the selected items, I couldn't figure out how to move multiple lines up or down.
Just cycle through the selectedItems() and use row() to get the row of each one.
for item in self.listWidget.selectedItems():
row = self.listWidget.row(item)
# ...
Consider that the selection model usually keeps the order in which items have been selected, so you should always reorder the items before moving them, and remember that if you move items down, they should be moved in reverse order.
def move_items(self, down=False):
items = []
for item in self.listWidget.selectedItems():
items.append((self.listWidget.row(item), item))
items.sort(reverse=down)
delta = 1 if down else -1
for row, item in items:
self.listWidget.takeItem(row)
self.listWidget.insertItem(row + delta, item)

delete items from 3 different lists

I need some help with deleting some items from some lists at the same time, when a button is clicked.
This is the code:
class Window(QMainWindow):
list_1 = [] #The items are strings
list_2 = [] #The items are strings
def __init__(self):
#A lot of stuff in here
def fillLists(self):
#I fill the lists list_1 and list_2 with this method
def callAnotherClass(self):
self.AnotherClass().exec_() #I do this to open a QDialog in a new window
class AnotherClass(QDialog):
def __init__(self):
QDialog.__init__(self)
self.listWidget = QListWidget()
def fillListWidget(self):
#I fill self.listWidget in here
def deleteItems(self):
item_index = self.listWidget.currentRow()
item_selected = self.listWidget.currentItem().text()
for i in Window.list_2:
if i == item_selected:
?????????? #Here is where i get confussed
When i open the QDialog with a combination of keys, i see in the QListWidget some items. In the deleteItems method, i get the index and the text from the item that i selected in the QListWidget. That works fine.
What i need to do is to delete the item from the list_1, list_2, and the QListWidget when i press a button (that i have already created).
How can i do this? Hope you can help me.
Python lists have a "remove" object that perform that action directly:
Window.list_2.remove(item_selected)
(with no need for your for loop)
If you ever need to perform more complex operations on the list items, you can retrieve an item's index with the index method instead:
position = Window.list_2.index(item_selected)
Window.list_2[position] += "(selected)"
And in some ocasions you will want to do a for loop getting to the actual index, as well as the content at that index of a list or other sequence. In that case, use the builtin enumerate.
Using the enumerate pattern, (if removedid not exist) would look like:
for index, content in enumerate(Window.list_2):
if content == item_selected:
del Window.list_2[index]
# must break out of the for loop,
# as the original list now has changed:
break
if you have the value, then just find its index in each list and then delete it. Something like:
item_selected = self.listWidget.currentItem().text()
i = Window.list_2.index(item_selected)
if i >= 0:
del Window.list_2[i]
You can also use directly Widow.list_x.remove(value) but it can throw an exception if the value does not exist.

QTreewidget only displays first letter of item name

Im learning how to use QTreeWidget and Im stuck adding new items to it. The QTreewidget itself is created with qtdesigner, so my idea was just to add items. eg:
tw = self.ui.treeWidget
item = QtGui.QTreeWidgetItem("TEST")
tw.addTopLevelItem(item)
But in the treewidget only appears the first letter of "TEST". Doesnt matter what I type, it always only displays the first letter and I have no idea why...
QTreeWidgetItem constructor expects a list of strings. Try this:
tw = self.ui.treeWidget
item = QtGui.QTreeWidgetItem(["TEST"])
tw.addTopLevelItem(item)
The QtGui.QTreeWidgetItem is expecting a list for different columns. You can simply wrap your text in a list
item = QtGui.QTreeWidgetItem(["TEST"])
or you can set the text for a specific column.
item = QtGui.QTreeWidgetItem()
item.setText(0, "TEST")

Python Query Result in QTreeWidget

I am working on python plugins.I used PyQt4 Designer.
I want to list query result into QTreeWidget.
My code is as follows:
c = self.db.con.cursor()
self.db._exec_sql(c, "select est from bio")
for row in c.fetchall():
item_value=unicode(row[0])
top_node1 = QTreeWidgetItem(item_value)
self.treeWidget.insertTopLevelItem(0, top_node1)
The query returns the values as:
But when i list these values into QTreeWidget using above code,it is shown as below :
Only first character is shown.If i change '0' to some other number in self.treeWidget.insertTopLevelItem(0, top_node1) ,nothing appears in QTreeWidget.
How do i do it????
thanx.
If you take a look at the documentation for a QTreeWidgetItem, you will see there are a number of possible constructors for creating an instance. Though none of which it seems you are using in a way that is going to give you desirable results. The closest match to the signature you are providing is:
QTreeWidgetItem ( const QStringList & strings, int type = Type )
What this is probably doing is taking your string (I am assuming row[0] is a string because I don't know which drivers you are using) and applying it as a sequence, which would fullfill the requiremets of QStringList. Thus what you are getting is populating multiple columns of your item with each letter of your string value. If this is what you wanted, then you would n eed to tell your widget to show more columns: self.treeWidget.setColumnCount(10). But this isn't what you are looking for I am sure.
More likely what you should be trying is to create a new item, then add the value to the desired column:
item = QTreeWidgetItem()
item.setText(0, unicode(row[0]))
self.treeWidget.insertTopLevelItem(0, item)
You can use the default constructor with no arguments, set the text value of the first column to your database record field value, and then add that item to the tree. You could also build up a list of the items and add them at once:
items = []
for row in c.fetchall():
item = QTreeWidgetItem()
item.setText(0, unicode(row[0]))
items.append(item)
self.treeWidget.insertTopLevelItems(0, items)
Your first aproach could be corrected just add a list to the widgetitem not a string like this:
top_node1 = QTreeWidgetItem([item_value])

Finding values in a list of key/value pairs

I have 2 lists
old_name_list = [a-1234, a-1235, a-1236]
new_name_list = [(a-1235, a-5321), (a-1236, a-6321), (a-1234, a-4321), ... ]
I want to search recursively if the elements in old_name_list exist in new_name_list and returns the associated value with it, for eg. the first element in old_name_list returns a-4321, second element returns a-5321, and so on until old_name_list finishes.
I have tried the following and it doesn't work
for old_name, new_name in zip(old_name_list, new_name_list):
if old_name in new_name[0]:
print new_name[1]
Is the method I am doing wrong or I have to make some minor changes to it? Thank you in advance.
Build a dict() based on your second list, and lookup in that.
old_name_list = ["a-1234", "a-1235", "a-1236"]
new_name_list = [("a-1235", "a-5321"), ("a-1236", "a-6321"), ("a-1234", "a-4321") ]
d = dict(new_name_list)
for n in old_name_list:
print d[n]
You do need to put quotes around strings like "a-1234".
Using a dictionary may be the best way to do this.
old_name_list = ['a-1234', 'a-1235', 'a-1236']
new_name_list = [('a-1235', 'a-5321'), ('a-1236', 'a-6321'), ('a-1234, a-4321')]
mapping = dict(new_name_list)
values = [mapping[item] if item in mapping for item in old_name_list]
print values
Use this:
found_items = [item[1] for item in new_name_list if item[0] in old_name_list]

Categories

Resources