PyQt右键单击QComboBox的Menu

时间:2016-04-14 05:39:00

标签: python pyqt pyqt4 pyqt5

我正在尝试使用右键菜单扩展QComboClass,并为其提供一个选项,将当前索引设置为-1(清除选择)。我无法调用上下文菜单甚至是右键单击事件。

class ComboBox(QComboBox):
    def __init__(self, *args, **kwargs):
        super(ComboBox, self).__init__()
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showMenu)

    def showMenu(self, pos):
        menu = QMenu()
        clear_action = menu.addAction("Clear Selection", self.clearSelection)
        action = menu.exec_(self.mapToGlobal(pos))

    def clearSelection(self):
        self.setCurrentIndex(-1)

有人能告诉我我做错了吗?

2 个答案:

答案 0 :(得分:1)

你可以试试吗,

def showMenu(self,event):
    menu = QMenu()
    clear_action = menu.addAction("Clear Selection", self)
    action = menu.exec_(self.mapToGlobal(event.pos()))
    if action == clear_action:
        self.clearSelection()

答案 1 :(得分:0)

你可以试试这个

import sys
from PyQt4 import QtGui
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QMenu



class Example(QtGui.QWidget):

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

        self.initUI()

    def initUI(self):

        self.lbl = QtGui.QLabel("Ubuntu", self)

        self.combo = QtGui.QComboBox(self)
        self.combo.setContextMenuPolicy(Qt.CustomContextMenu)
        self.combo.customContextMenuRequested.connect(self.showMenu)
        self.combo.addItem("Ubuntu")
        self.combo.addItem("Mandriva")
        self.combo.addItem("Fedora")
        self.combo.addItem("Red Hat")
        self.combo.addItem("Gentoo")

        self.combo.move(50, 50)
        self.lbl.move(50, 150)

        self.combo.activated[str].connect(self.onActivated)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QtGui.QComboBox')
        self.show()

    def showMenu(self,pos):
        menu = QMenu()
        clear_action = menu.addAction("Clear Selection")
        action = menu.exec_(self.mapToGlobal(pos))
        if action == clear_action:
            self.combo.setCurrentIndex(0)

    def onActivated(self, text):

        self.lbl.setText(text)
        self.lbl.adjustSize()

def main():

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


if __name__ == '__main__':
    main()