Search code examples
pythonpyqtpyqt5qpushbuttonqlistwidget

How to get the item from a QListWidget object as a string once selected and a QButton pushed


I have been rocking my head and fruitlessly searching for a way for me to click an item on a PyQt5 GUI and then proceed to press the delete button to delete that item from my database. I kind of need to get the string of this item (which composes of someone's last name followed by a comma, and then the first name) since I need to access my database to delete this item from there by passing in the name of the person on the list.

See my code below:

import sqlite3 as sql3
import sys
from PyQt5.QtWidgets import (QMessageBox,QPushButton,QApplication, QWidget, QLineEdit,QDesktopWidget,QLabel, QListWidget,QVBoxLayout, QListWidgetItem)
from PyQt5.QtGui import QIcon, QFont

class deleteUser(QWidget): #QWidget is the base class for all GUI elements in the PyQt5.

    def __init__(self):      
        super().__init__() #initializes the main window
        self.title = "Employee Management System Menu"
        self.x = 60
        self.y = 100
        self.width = 400
        self.height = 400
        self.mainTitle()
        self.buttons()
        self.list_customer()
        self.initUI()
    
    def mainTitle(self):
        self.MainTitle = QLabel("Delete Admins/Users", self)
        self.MainTitle.move(self.x+10, self.y-50)
        self.MainTitle.setFont(QFont('Times', 20))
        
    def buttons(self):       
        self.back_ = QPushButton("back", self)
        self.back_.setToolTip("Press to enter App Menu!")
        self.back_.move(self.x+100,self.y+260)
        self.back_.clicked.connect(self.back_clicked)
        
        self.delete_u = QPushButton("delete", self)
        self.delete_u.setToolTip("Press to delete an admin!")
        self.delete_u.move(self.x+100,self.y+230)
        self.delete_u.setStyleSheet('color: red;')
        self.delete_u.clicked.connect(self.deleteClicked)
        
    def push(self, item):       
        self.item = item.text()
        
    def back_clicked(self):
        self.dialog = am.appMenu()
        self.dialog.show()
        self.close()
    
    def list_customer(self):
        self.l_c = QListWidget(self)
        self.l_c.setGeometry(self.x, self.y-15, 265, 220) 
        db = sql3.connect('appDB.db')
        cr = db.cursor()
        cr.execute("SELECT userId, lastName, firstName FROM users")
        for row in cr:
            self.s = '{}:\t {}, {}'.format(row[0], row[1],row[2])
            self.item1 = QListWidgetItem(self.s)
            self.l_c.addItem(self.item1)
        self.l_c.itemClicked.connect(self.push)
        
    def deleteClicked(self):   
        try:
            
            print(self.item)
            print("this button works")
            
        except AttributeError:
            
            QMessageBox.information(self,"ALERT!", "You didn't select a user")

    
    def initUI(self):
        self.setWindowTitle(self.title)
        self.resize(self.width, self.height)
        self.setWindowIcon(QIcon("python.ico"))
        self.center()
        self.show()
    
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = deleteUser()
    sys.exit(app.exec_())

What I want to essentially do is not have to use self.l_c.itemClicked.connect(self.push) to create a whole new function def push(self, item): just so I could access the item as a string. Is there a way to simply bind a variable to whatever I am clicking on currently without having to activate the clicking event and create a whole new function?


Solution

  • As already pointed out in the comments, currentItem() returns the currently selected list item. Hence, your can skip the clicked event + additional function and just replace your delete function by:

    def deleteClicked(self):   
        try:
            print(self.l_c.currentItem().text())
            print("this button works") 
        except AttributeError:
            
            QMessageBox.information(self,"ALERT!", "You didn't select a user")
    

    You can further use the currentItemChanged event to directly react to user interaction with the list, see e.g. this stack answer