python - 从 qComboBox 弹出菜单捕获鼠标按钮按下信号

标签 python pyqt4 signals-slots popupmenu qcombobox

我制作了多选QComboBox。项目是可检查的(每个项目都有复选框和文本值)。 CheckBox 只有在用户点击它时才会被选中。我想要的是在用户单击文本值时捕获信号,以便我可以设置选中它旁边的复选框。如何做到这一点?

enter image description here

这就是我将模型设置为组合框的方式:

areas = ["Area one", "Area two", "Area three", "Area four"]
model = QtGui.QStandardItemModel(5, 1)# 5 rows, 1 col

firstItem = QtGui.QStandardItem("---- Select area(s) ----")
firstItem.setBackground(QtGui.QBrush(QtGui.QColor(200, 200, 200)))
firstItem.setSelectable(False)
model.setItem(0, 0, firstItem)

for i,area in enumerate(areas):
    item = QtGui.QStandardItem(area)
    item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    item.setData(QtCore.Qt.Unchecked, QtCore.Qt.CheckStateRole)
    model.setItem(i+1, 0, item)

self.ui.comboBox.setModel(model)        
self.ui.comboBox.installEventFilter(self)

我添加了事件过滤器来阻止轮子事件,所以 firstItem 的文本总是显示为“已选择”

def eventFilter(self,target,event):
    if target == self.ui.comboBox:
        if(event.type()== QtCore.QEvent.Wheel):
            #wheel event is blocked here
            return True
    return False

最佳答案

您需要将处理程序连接到 pressed signal组合的 view :

    self.ui.comboBox.view().pressed.connect(self.handleItemPressed)
    ...

    def handleItemPressed(self, index):
        item = self.ui.comboBox.model().itemFromIndex(index)
        if item.checkState() == QtCore.Qt.Checked:
            item.setCheckState(QtCore.Qt.Unchecked)
        else:
            item.setCheckState(QtCore.Qt.Checked)

关于python - 从 qComboBox 弹出菜单捕获鼠标按钮按下信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186779/

相关文章:

python - 多变量线性回归与 scipy linregress

qt - 添加信号/插槽后,简单的 Qt 应用程序拒绝编译

python - 更改变量值时的 PyQt 事件

c++ - QLineWidget returnPressed 信号不工作

python - 从多个文件读取行

python - 使用 python click 进行类似 SSH 或 sudo 的行为

python - 无法将 Owlready 库导入 Python

python - pyqt4小部件出现在布局之外

python - PyQt : How to expand all children in a QTreeWidget

python - 如何从一个类发出 Qtsignal,从而导致在 pyqt 中从其父类发出 Qtsignal