如何找到QComboBox的下拉箭头?

问题描述 投票:0回答:1

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

python pyside2 qcombobox
1个回答
0
投票

您必须检测鼠标单击的位置并确认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()
© www.soinside.com 2019 - 2024. All rights reserved.