【问题标题】:How to find the drop down arrow of QComboBox is clicked?如何找到 QComboBox 的下拉箭头被点击?
【发布时间】:2020-04-26 14:25:17
【问题描述】:

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

【问题讨论】:

    标签: python pyside2 qcombobox


    【解决方案1】:

    你必须检测鼠标点击的位置并验证复杂控件是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()
    

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 2012-07-14
      • 2020-10-29
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多