简体   繁体   English

如何获取选定的项目 QlistWidget pyqt

[英]How to get selected item QlistWidget pyqt

当用户在 QlistWidget 中选择一个项目然后单击按钮以获取此元素时,我想获取所选元素

Try this one:试试这个:

from PyQt5.QtWidgets import (QWidget, QListWidget, QVBoxLayout, QApplication)
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()


        self.l = QListWidget()
        for n in range(10):
            self.l.addItem(str(n))

        self.l.itemSelectionChanged.connect(self.selectionChanged)

        vbox = QVBoxLayout()
        vbox.addWidget(self.l)

        self.setLayout(vbox)
        self.setGeometry(300, 300, 300, 300)
        self.show()

    def selectionChanged(self):
        print("Selected items: ", self.l.selectedItems())


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

With this approach you will have all items, selected by clicking, using keyboard arrows or dragging the mouse on them, printed.使用这种方法,您将打印通过单击、使用键盘箭头或在其上拖动鼠标来选择的所有项目。

You can use itemActivated signal from QListWidget class and bind it to some of your method.您可以使用 QListWidget 类中的 itemActivated 信号并将其绑定到您的某些方法。

yourQListWidget.itemActivated.connect(itemActivated_event)

def itemActivated_event(item)
    print(item.text())

Now everytime user click on some item in your QListWidget the text inside of this item is printed.现在,每次用户单击 QListWidget 中的某个项目时,都会打印该项目内的文本。

Binding a method to the itemClicked signal from QListWidget also seems to work:将方法绑定到来自 QListWidget 的 itemClicked 信号似乎也有效:

yourQListWidget.itemClicked.connect(itemClicked_event)

def itemClicked_event(item):
    print(item.text())

For me, the itemClicked signal works with single-clicking the item and itemActivated works with double clicking.对我来说, itemClicked 信号适用于单击项目,而 itemActivated 则适用于双击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM