一旦选择并按下 QButton,如何从 QListWidget 对象中获取项目作为字符串

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

我一直在摇头晃脑地寻找一种方法,让我在 PyQt5 GUI 上单击一个项目,然后继续按删除按钮从我的数据库中删除该项目。我有点需要获取这个项目的字符串(由某人的姓氏后跟一个逗号,然后是名字组成)因为我需要访问我的数据库以通过传递人名从那里删除这个项目在名单上。

查看下面我的代码:

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_())

我基本上想做的是不必使用 self.l_c.itemClicked.connect(self.push) 来创建一个全新的函数 def push(self, item): 这样我就可以将项目作为字符串访问。有没有一种方法可以简单地将变量绑定到我当前点击的任何内容,而无需激活点击事件并创建一个全新的功能?

正如评论中已经指出的那样,currentItem() returns 当前选择的列表项。因此,您可以跳过点击事件 + 附加功能,只需将删除功能替换为:

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")

您可以进一步使用 currentItemChanged event to directly react to user interaction with the list, see e.g. this stack answer