gpt4 book ai didi

python - Pyqt5 查找 QlistWidgetItem 的行

转载 作者:行者123 更新时间:2023-12-01 01:12:12 25 4
gpt4 key购买 nike

我有一个自定义小部件,它有一个与其关联的按钮。有没有办法,当单击自定义小部件上的按钮时,我可以找出当前自定义小部件在 QListWidget 中的哪一行?

文件

Main_GUI.py

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(353, 237)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setObjectName("listWidget")
self.gridLayout.addWidget(self.listWidget, 0, 0, 1, 1)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 1, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 353, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)

self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Add Item"))

CustomWidget_GUI.py

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Table_Widget_Insert(object):
def setupUi(self, Table_Widget_Insert):
Table_Widget_Insert.setObjectName("Table_Widget_Insert")
Table_Widget_Insert.resize(278, 66)
self.horizontalLayout = QtWidgets.QHBoxLayout(Table_Widget_Insert)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(Table_Widget_Insert)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.line = QtWidgets.QFrame(Table_Widget_Insert)
self.line.setFrameShape(QtWidgets.QFrame.VLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.horizontalLayout.addWidget(self.line)
self.pushButton = QtWidgets.QPushButton(Table_Widget_Insert)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)

self.retranslateUi(Table_Widget_Insert)
QtCore.QMetaObject.connectSlotsByName(Table_Widget_Insert)

def retranslateUi(self, Table_Widget_Insert):
_translate = QtCore.QCoreApplication.translate
Table_Widget_Insert.setWindowTitle(_translate("Table_Widget_Insert", "Form"))
self.label.setText(_translate("Table_Widget_Insert", "TextLabel"))
self.pushButton.setText(_translate("Table_Widget_Insert", "Row Number"))

自定义Widget.py

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from CustomWidget_GUI import *


class SignalsObject(QObject):
listWidgetCurrentIndex = pyqtSignal(str)

class CustomListEntry(QWidget):

def __init__(self, parent=None):
QWidget.__init__(self,parent)
self.CustomUi = Ui_Table_Widget_Insert()
self.CustomUi.setupUi(self)
self.setUpMainUiFunction()
self.signals = SignalsObject()

def setUpMainUiFunction(self):
self.CustomUi.pushButton.clicked.connect(self.rowNumber)

def setlabel(self,label):
self.CustomUi.label.setText(label)

def setButtonName(self,name):
self.CustomUi.pushButton.setObjectName(name)

def rowNumber(self):
sender = self.sender()
name = sender.objectName().split("__")
entryNumber = name[1]

self.signals.listWidgetCurrentIndex.emit(entryNumber)

主程序.py

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from Main_GUI import *

from CustomWidget import *




class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
QWidget.__init__(self, parent)
self.MainUi = Ui_MainWindow()
self.MainUi.setupUi(self)
self.setUpMainUiFunction()
self.listEntryNumber = 0


def setUpMainUiFunction(self):
self.MainUi.pushButton.clicked.connect(self.addCustomEntry)


def addCustomEntry(self):
self.listEntryNumber = self.listEntryNumber + 1

CustomWidget = CustomListEntry()
CustomWidget.setObjectName("entry"+str(self.listEntryNumber))

CustomWidget.setlabel("Entry Number= "+str(self.listEntryNumber))

CustomWidget.signals.listWidgetCurrentIndex.connect(self.findListIndex)

CustomWidget.setButtonName("button__"+ str(self.listEntryNumber))

myQListWidgetItem = QListWidgetItem(self.MainUi.listWidget)
#pdb.set_trace()
myQListWidgetItem.setSizeHint(CustomWidget.sizeHint())

self.MainUi.listWidget.addItem(myQListWidgetItem)
self.MainUi.listWidget.setItemWidget(myQListWidgetItem, CustomWidget)

def findListIndex(self,entryNumber):
print(entryNumber)
# items = self.MainUi.feederSchedule_listWidget.findItems("entry"+entryNumber,Qt.MatchExactly)
items = self.MainUi.listWidget.findChildren(CustomListEntry,"entry"+entryNumber)
# item = self.MainUi.feederSchedule_listWidget.findItems(items, Qt.MatchRegExp)
if len(items) > 0:
for item in items:
print ("row number of found item =",self.MainUi.listWidget.row(item))


if __name__ == "__main__":
#os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
app = QtWidgets.QApplication(sys.argv)
MainWindow = MainWindow()
MainWindow.show()
sys.exit(app.exec_())

我可以看到它能够找到 QListWidget 中的所有项目,但我似乎无法将我的自定义对象与列出的其中之一进行匹配。这就是我无法找到该行的地方。另外,在我的实际程序中,我将删除行。条目号必须与行号分开

最佳答案

在这种情况下,最好实现一个自定义的 QListWidget,它允许您获取行,小部件不应该知道它属于哪一行,但列表小部件应该知道。

因此,我将创建以下自定义 QListWidget,它发出 clicked_widget 信号,指示发出 clicked 信号的小部件的行号:

clickablelistwidget.py

from PyQt5 import QtCore, QtWidgets

class ClickableListWidget(QtWidgets.QListWidget):
clicked_widget = QtCore.pyqtSignal(int)

def append_widget(self, widget_clickable):
item = QtWidgets.QListWidgetItem()
self.addItem(item)
item.setSizeHint(widget_clickable.sizeHint())
self.setItemWidget(item, widget_clickable)
if hasattr(widget_clickable, "clicked"):
if isinstance(widget_clickable.clicked, QtCore.pyqtBoundSignal):
widget_clickable.clicked.connect(self.on_clicked)

@QtCore.pyqtSlot()
def on_clicked(self):
widget = self.sender()
gp = widget.mapToGlobal(QtCore.QPoint())
lp = self.viewport().mapFromGlobal(gp)
item = self.itemAt(lp)
row = self.row(item)
self.clicked_widget.emit(row)

然后修改Main_GUI.py文件以用新类替换QListWidget:

Main_GUI.py

from PyQt5 import QtCore, QtGui, QtWidgets
from clickablelistwidget import ClickableListWidget

class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(353, 237)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.listWidget = ClickableListWidget(self.centralwidget) # <---
self.listWidget.setObjectName("listWidget")
self.gridLayout.addWidget(self.listWidget, 0, 0, 1, 1)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 1, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 353, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)

self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Add Item"))

您的自定义小部件已修改,以便在按下按钮时发出单击信号:

CustomWidget.py

import sys
from PyQt5 import QtCore, QtWidgets
from CustomWidget_GUI import Ui_Table_Widget_Insert

class CustomListEntry(QtWidgets.QWidget, Ui_Table_Widget_Insert):
clicked = QtCore.pyqtSignal()

def __init__(self, parent=None):
super(CustomListEntry, self).__init__(parent)
self.setupUi(self)
self.setUpMainUiFunction()

def setUpMainUiFunction(self):
self.pushButton.clicked.connect(self.clicked)

def setlabel(self,label):
self.label.setText(label)

现在可以在主文件中使用了:

Main.py

import sys
from PyQt5 import QtCore, QtWidgets
from Main_GUI import Ui_MainWindow
from CustomWidget import CustomListEntry

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.setUpMainUiFunction()

def setUpMainUiFunction(self):
self.pushButton.clicked.connect(self.addCustomEntry)
self.listWidget.clicked_widget.connect(self.on_clicked_widget)

@QtCore.pyqtSlot()
def addCustomEntry(self):
listEntryNumber = self.listWidget.count()
custom_widget = CustomListEntry()
custom_widget.setlabel("Entry Number= {}".format(listEntryNumber))
self.listWidget.append_widget(custom_widget)

@QtCore.pyqtSlot(int)
def on_clicked_widget(self, row):
print("row number of found item = {}".format(row))

if __name__ == "__main__":
#os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
app = QtWidgets.QApplication(sys.argv)
MainWindow = MainWindow()
MainWindow.show()
sys.exit(app.exec_())

最后您的文件夹必须具有以下结构:

├── clickablelistwidget.py
├── CustomListWidget.py
├── CustomWidget_GUI.py
├── CustomWidget.py
├── Main_GUI.py
└── Main.py
<小时/>

此方法的优点是它解耦了类,使其易于重用。您不必求助于 objectName 或将 QListWidgetItem 注入(inject)到小部件中,如果我们有多种类型的小部件,这可能会很乏味。 :-)。

关于python - Pyqt5 查找 QlistWidgetItem 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54753024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com