如何找到单击QComboBox的下拉箭头?

时间:2020-04-26 14:25:17

标签: python pyside2 qcombobox

我有一个QComboBox,单击该QComboBox的下拉箭头时,我需要设置一个名称列表。那么,PySide2是否有任何功能可以确定用户是否单击了该下拉箭头,在此之后,我想获取用户选择的索引。如果有人对PySide2中的操作有任何想法。

1 个答案:

答案 0 :(得分:1)

您必须检测鼠标单击的位置并验证complexControl是否为QStyle :: SC_ComboBoxArrow:

import sys
from PySide2 import QtCore, QtGui, QtWidgets


class ComboBox(QtWidgets.QComboBox):
    arrowClicked = QtCore.Signal()

    def mousePressEvent(self, event):
        super().mousePressEvent(event)
        opt = QtWidgets.QStyleOptionComboBox()
        opt.initFrom(self)
        opt.subControls = QtWidgets.QStyle.SC_All
        opt.activeSubControls = QtWidgets.QStyle.SC_None
        opt.editable = self.isEditable()
        cc = self.style().hitTestComplexControl(
            QtWidgets.QStyle.CC_ComboBox, opt, event.pos(), self
        )
        if cc == QtWidgets.QStyle.SC_ComboBoxArrow:
            self.arrowClicked.emit()


def main():
    app = QtWidgets.QApplication(sys.argv)
    w = ComboBox()
    w.addItems(["option1", "option2", "option3"])
    w.show()

    w.arrowClicked.connect(
        lambda: print("index: {}, value: {}".format(w.currentIndex(), w.currentText()))
    )
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()