Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

python - Catch mouse button pressed signal from qComboBox popup menu

I have made multi-select QComboBox. Items are checkable (every item have check box and text value). CheckBox is checked only when user click on it. What I want is to catch signal when user click on text value so I can set check box next to it checked. How to do that?

enter image description here

This is how I set model to combo box:

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)

I've added event filter to block wheel event,so firstItem's text is always shown as "chosen"

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to connect a handler to the pressed signal of the combo's 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...