Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from QListWidget in PyQt5

I am trying to make a refresh button in pyqt5. I am building a desktop app. I wrote the code that scans particular folder and saves filenames and their paths as an array.

Array values are added to QListWidget as items

self.sampleChoose_list.addItems(sample_directory[0])

I am trying to make a function that refreshes values of the array and passes it to QListWidget.

Something like this

self.refreshSamples.clicked.connect(self.refreshSample)

def refreshSample(self): 
    sample_directory = []
    sample_files = []
    for (dirpath, dirnames, filenames) in walk('./Samples'):
        filenames = [f for f in filenames if not f[0] == '.']
        sample_files.extend(filenames)
        break
    the_dir = "Samples"
    paths = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir) if not filename.startswith('.')]    

    sample_directory.append(sample_files)
    sample_directory.append(paths)

    self.sampleChoose_list.addItems(sample_directory[0])

The problem that I struggle with is: when I push refresh button, new items get added, but the old ones are not deleted. How to remove items from QListWidget?

like image 352
Graygood Avatar asked Mar 02 '18 11:03

Graygood


People also ask

How do I remove an item from QListWidget?

You may use this code to remove: QListWidgetItem *it = ui->listWidget->takeItem(ui->listWidget->currentRow()); delete it; Keep in mind that "takeItem" does not delete the object. Hi, friend, welcome devnet.

What is QWidget PyQt5?

The QWidget widget is the base class of all user interface objects in PyQt5. We provide the default constructor for QWidget . The default constructor has no parent. A widget with no parent is called a window.


1 Answers

use QListWidget.clear() and it

Removes all items and selections in the view.

for am more selective approuch you can use QListWidget.takeItem( index ), it

Removes and returns the item from the given row in the list widget


Official Docs: clear()
Official Docs: takeItem()

like image 196
Skandix Avatar answered Oct 02 '22 13:10

Skandix