Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send the selected item in the listWidget to another function as a parameter

Tags:

python

qt4

pyqt4

Whenever I click any function in the list widget, it ran a specific function. Now I want to send the item itself, as a parameter to that function. Here is the code:

QtCore.QObject.connect(self.listWidget, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.test)

def test(self):
    print 'hello'

Instead I want:

def test(self,item):
        print item
like image 957
Jack Avatar asked Dec 16 '22 03:12

Jack


1 Answers

That should already work - when itemClicked is emitted it sends the clicked QListWidgetItem as a parameter. You just need to edit your test function to accept an extra parameter, and that will be your QListWidgetItem.

from PyQt4.QtCore import QCoreApplication, Qt
from PyQt4.QtGui import QListWidget, QListWidgetItem, QApplication

import sys

class MyList(QListWidget):
    def __init__(self):
        QListWidget.__init__(self)
        self.add_items()
        self.itemClicked.connect(self.item_click)

    def add_items(self):
        for item_text in ['item1', 'item2', 'item3']:
            item = QListWidgetItem(item_text)
            self.addItem(item)

    def item_click(self, item):
        print item, str(item.text())

if __name__ == '__main__':
    app = QApplication([])
    myList = MyList()
    myList.show()
    sys.exit(app.exec_())

In the above example you'll see a QListWidget with three items. When you click an item the item along with the item's text will be printed to the console.

like image 88
Gary Hughes Avatar answered Dec 28 '22 09:12

Gary Hughes