0

如何确保仅在单击 QListWidgetItem "Item 1" 而不是 QListWidgetItem "Item 2" 时才调用 do_something() 函数?

在下面的实现中,每次单击其中一个项目时都会调用 do_something() 函数。

from PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QHBoxLayout, QListWidgetItem
import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.list_widget = QListWidget()
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.list_widget)
        self.list_widget.insertItem(1, QListWidgetItem("Item 1"))
        self.list_widget.insertItem(2, QListWidgetItem("Item 2"))
        self.list_widget.itemClicked.connect(self.do_something)
        self.setLayout(self.layout)
        self.show()

    def do_something(self):
        print("It was clicked on item 1")


App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
4

1 回答 1

0

解决方法是获取按下项所在的行,并验证为0:

from PyQt5.QtCore import pyqtSlot

# ...

@pyqtSlot("QListWidgetItem*")
def do_something(self, item):
    if self.list_widget.row(item) == 0:
        print("It was clicked on item 1")
于 2019-11-17T16:53:26.107 回答