QListWidget处理来自click和itemSelectionChanged的多个信号

时间:2017-02-07 22:27:35

标签: python pyqt

我有两个列表小部件,基本上是项目选择器。当我在任一列表中选择一个项目时,我需要它来触发一个方法。这里只有一个问题。我需要在选择更改或单击某个项目时执行该过程,但我不希望该事件发生两次,这是我遇到的问题

有点难以描述,但请看下面的代码。

场景1:两个列表仅连接" itemSelectionChanged" 点击"奶酪" 点击"否" 现在两者都被选中,当你交替点击它们时没有任何事情发生,因为没有选择正在改变,但是当我从不同的列表中选择一个项目时,我需要调用something_happened方法。

场景2:两个列表仅连接"点击" 点击后会发生一些事情,但当我点击并拖动以更改选择时,不会触发任何事件,因为"点击"没有发生,并且itemSelectionChanged没有连接到任何东西。当选择以这种方式改变时,我需要调用something_happened方法。

场景3:两个列表都连接" itemSelectionChanged"还有"点击" 单击并拖动以更改选择会使某些事情发生(很好),但是当我执行单个"单击"在一个新项目上,两个信号都被发送,我想要发生的事件发生两次(坏)。

鉴于上述情况,我希望同时实现以下所有目标:

  • 当我点击一个新项目(同时同时发出itemSelectionChanged和itemClicked导致两个事件)时,处理仅一个事件。
  • 点击已选择的项目(发出项目点击信号)时处理一个事件
  • 通过单击并拖动(发出itemSelectionChagned信号)更改选择时处理一个事件

以下是示例代码:

from PyQt4 import QtGui
QtWidgets = QtGui
# from PyQt5 import QtWidgets
import sys
import time


def something_happened():
    print(time.time())

app = QtWidgets.QApplication(sys.argv)

widget = QtWidgets.QWidget(None)
vlay = QtWidgets.QVBoxLayout(widget)

list_widget1 = QtWidgets.QListWidget(None)
list_widget1.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
list_widget1.addItems(("Cheese", "Whiz", "tastes", "great"))
list_widget1.itemSelectionChanged.connect(something_happened)
list_widget1.clicked.connect(something_happened)

list_widget2 = QtWidgets.QListWidget(None)
list_widget2.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
list_widget2.addItems(("No", "it", "tastes", "bad"))
list_widget2.itemSelectionChanged.connect(something_happened)
# list_widget2.clicked.connect(something_happened)

vlay.addWidget(list_widget1)
vlay.addWidget(list_widget2)

widget.show()

app.exec_()

1 个答案:

答案 0 :(得分:3)

在这个例子中,我是QListWidget的子类。这没有必要,但我认为如果您在窗口小部件本身中封装选择更改的决定,它将使代码更清晰。我制作了两种类型的小部件,每种小部件都有自己的行为,以决定选择是否改变。你可以使用mousePress / mouseRelease / selectionChanged组合,希望这段代码能为你提供所需的工具。 运行此程序,并注意两个小部件之间的差异。

class SomeFrame(object):
    """A container to place all the widgets, and control
       present the output from the selections.
    """
    def __init__(self):
        self.frame = QtWidgets.QFrame()

        # Creating content
        list_widget1 = MyQListWidgetA()
        list_widget1.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
        list_widget1.addItems(("Cheese", "Whiz", "tastes", "great"))

        list_widget2 = MyQListWidgetB()
        list_widget2.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
        list_widget2.addItems(("No", "it", "tastes", "bad"))

        # Creating Layout
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(list_widget1)
        layout.addWidget(list_widget2)

        self.frame.setLayout(layout)

        # Connections
        from functools import partial
        list_widget1.selection_changed.connect(partial(self.selectionChangedCB, 'list_1'))
        list_widget2.selection_changed.connect(partial(self.selectionChangedCB, 'list_2'))

        self.frame.show()

    def selectionChangedCB(self, list_name, selected_items):
        print(list_name + ' changed: ' + str(selected_items))


from PyQt5 import QtWidgets, QtCore
class MyQListWidgetA(QtWidgets.QListWidget):
    """This widget emits selection_changed whenever its
       itemSelectionChanged signal is emitted, AND there
       was an actual change in the selected items.
    """
    selection_changed = QtCore.pyqtSignal(object)

    def __init__(self):
        QtWidgets.QListWidget.__init__(self)

        self.selected_items = set()

        self.itemSelectionChanged.connect(self.something_happened)

    def something_happened(self):
        # Create a set of the newly selected items, so we can compare
        # to the old selected items set
        newly_selected_items = set([item.text() for item in self.selectedItems()])
        if newly_selected_items != self.selected_items:
            # Only emit selection_changed signal if a change was detected.
            self.selected_items = newly_selected_items
            self.selection_changed.emit(self.selected_items)


class MyQListWidgetB(QtWidgets.QListWidget):
    """This widget emits selection_changed whenever it is pressed
       (mimic "clicked" signal) and again when the user is done
       selecting the items (mouse release) IFF the selection
       has changed.
    """
    selection_changed = QtCore.pyqtSignal(object)

    def __init__(self):
        QtWidgets.QListWidget.__init__(self)

        self.selected_items = set()

    def something_happened(self, initial_click=False):
        # Create a set of the newly selected items, so we can
        # compare to the old selected items set
        newly_selected_items = set([item.text() for item in self.selectedItems()])
        if newly_selected_items != self.selected_items:
            # Only emit selection_changed signal if a change was detected
            self.selected_items = newly_selected_items
            self.selection_changed.emit(self.selected_items)

    def mousePressEvent(self, event):
        QtWidgets.QListWidget.mousePressEvent(self, event)
        self.something_happened()

    def mouseReleaseEvent(self, event):
        QtWidgets.QListWidget.mouseReleaseEvent(self, event)
        self.something_happened()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)         
    theFrame = SomeFrame()
    sys.exit(app.exec_())

编辑:我意识到我从未说过“当我点击已经选中的项目(发出项目点击信号)时处理一个事件”。 我将其视为单项单击,但也可以针对相同的多项目点击进行解决(使用mouseReleaseEvent,并比较旧的新列表)。 只需添加MyQListWidgetC,并将其连接到两个信号。 B和C之间的主要区别在于,在mousePressEvent中我们检查是否按下了单个项目,以及它是否是同一个项目。

class MyQListWidgetC(QtWidgets.QListWidget):
    """This widget emits selection_changed whenever it is pressed
       (mimic "clicked" signal) and again when the user is done
       selecting the items (mouse release) IFF the selection
       has changed. If a single item was clicked, AND it is the
       same item, the widget will emit same_item_clicked, which
       the owner can listen to and decide what to do.
    """
    selection_changed = QtCore.pyqtSignal(object)
    same_item_clicked = QtCore.pyqtSignal(object)

    def __init__(self):
        QtWidgets.QListWidget.__init__(self)

        self.selected_items = set()

    def something_happened(self, initial_click=False):
        # Create a set of the newly selected items, so we can
        # compare to the old selected items set
        newly_selected_items = set([item.text() for item in self.selectedItems()])
        if newly_selected_items != self.selected_items:
            # Only emit selection_changed signal if a change was detected
            self.selected_items = newly_selected_items
            self.selection_changed.emit(self.selected_items)

    def mousePressEvent(self, event):
        QtWidgets.QListWidget.mousePressEvent(self, event)
        newly_selected_items = set([item.text() for item in self.selectedItems()])
        if len(newly_selected_items) == 1 and newly_selected_items == self.selected_items:
            self.same_item_clicked.emit(self.selected_items)
        else:
            self.something_happened()

    def mouseReleaseEvent(self, event):
        QtWidgets.QListWidget.mouseReleaseEvent(self, event)
        self.something_happened()