📜  PyQt5 QListWidget – 获取当前项目(1)

📅  最后修改于: 2023-12-03 15:03:58.286000             🧑  作者: Mango

PyQt5 QListWidget – 获取当前项目

在 PyQt5 中,QListWidget 是用于显示列表控件的基类。在 QListWidget 中,我们可以使用 currentRow() 方法获取当前的项目。

获取当前项目的方法
def get_current_item(self):
    current_item = self.list_widget.currentItem()
    if current_item:
        return current_item.text()
    else:
        return None

在这个方法中,我们首先调用 currentItem() 方法获取当前的项目。如果列表控件为空或没有任何项目被选中,这个方法将返回 None。如果有项目被选中,我们可以调用 text() 方法来获取当前项目的文本内容。

完整示例
from PyQt5.QtWidgets import QApplication, QListWidget, QWidget, QVBoxLayout, QLabel
import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.list_widget = QListWidget()
        self.list_widget.addItems(["Item1", "Item2", "Item3", "Item4"])
        self.list_widget.currentRowChanged.connect(self.on_item_select)

        self.label = QLabel()

        layout = QVBoxLayout()
        layout.addWidget(QLabel("Select an item:"))
        layout.addWidget(self.list_widget)
        layout.addWidget(self.label)

        self.setLayout(layout)

    def on_item_select(self, index):
        item_text = self.get_current_item()
        self.label.setText(f"Selected item: {item_text}")

    def get_current_item(self):
        current_item = self.list_widget.currentItem()
        if current_item:
            return current_item.text()
        else:
            return None

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

在这个示例中,我们创建了一个包含四个项目的 QListWidget。当用户选择一个新项目时,我们在标签中显示选中项目的文本内容。在 on_item_select 方法中,我们调用 get_current_item 方法来获取当前项目的文本内容。如果没有项目被选中,这个方法将返回 None。