我有一个QComboBox,当该QComboBox的下拉箭头被点击时,我需要设置一个名称列表。那么PySide2有没有什么函数可以查出用户是否点击了那个下拉箭头,之后我想得到用户选择的索引。如果谁有什么办法可以在PySide2中实现这个功能。
你必须检测到鼠标点击的位置,并验证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()