【问题标题】:What is the signal for user clicks the down arrow on the QComboBox?用户单击 QComboBox 上的向下箭头的信号是什么?
【发布时间】:2021-03-19 02:58:59
【问题描述】:

每当用户单击组合框上的向下箭头时,我都需要执行一个方法。我已经尝试了文档中列出的信号,但没有一个有效。

from PyQt5.QtWidgets import *
import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.combo = QComboBox(self)
        self.combo.signal.connect(self.mymethod)
        self.show()

    def mymethod(self):
        print('hello world')

app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

【问题讨论】:

    标签: python pyqt pyqt5 qcombobox


    【解决方案1】:

    按下向下箭头时不会发出任何信号,但您可以创建覆盖 mousePressEvent 方法并验证该元素是否被按下:

    import sys
    
    from PyQt5.QtCore import pyqtSignal, Qt
    from PyQt5.QtWidgets import (
        QApplication,
        QComboBox,
        QStyle,
        QStyleOptionComboBox,
        QVBoxLayout,
        QWidget,
    )
    
    
    class ComboBox(QComboBox):
        arrowClicked = pyqtSignal()
    
        def mousePressEvent(self, event):
            super().mousePressEvent(event)
            opt = QStyleOptionComboBox()
            self.initStyleOption(opt)
            sc = self.style().hitTestComplexControl(
                QStyle.CC_ComboBox, opt, event.pos(), self
            )
            if sc == QStyle.SC_ComboBoxArrow:
                self.arrowClicked.emit()
    
    
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.combo = ComboBox()
            self.combo.arrowClicked.connect(self.mymethod)
    
            lay = QVBoxLayout(self)
            lay.addWidget(self.combo)
            lay.setAlignment(Qt.AlignTop)
    
        def mymethod(self):
            print("hello world")
    
    
    if __name__ == "__main__":
    
        app = QApplication(sys.argv)
        win = Window()
        win.show()
        sys.exit(app.exec_())
    

    【讨论】:

    • 我正在使用 qt 设计器,在我的代码中我使用 uic.loadUi() 加载 UI 文件。在这种情况下,我怎样才能发出arrowClicked 信号?
    • @Mohammad 你必须推广这个小部件:stackoverflow.com/search?q=%5Bpyqt%5D+promote
    猜你喜欢
    • 2012-07-14
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多