PyQt双重功能ENTER按键按压

2024-05-16 05:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是PyQt5和python3.6。我想使用ENTER(或RETURN)键进行双重用途。在

如果用户在组合框中输入文本,然后按ENTER键,那么我希望将组合框中的文本追加到列表中。在所有其他情况下,我希望ENTER键作为按钮的快捷方式。在

我找不到按下ENTER时句柄的正确决定。这是一个代码示例。我在寻找returnDecision(self)函数中的一个决定(朝向脚本的底部)。在

import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QShortcut
from PyQt5.QtWidgets import QComboBox
from PyQt5.QtGui import QKeySequence   
from PyQt5.QtCore import Qt, QSize

class Example(QWidget):

    def __init__(self):
        super().__init__()        
        self.initUI()        

    def initUI(self):
        self.setGeometry(300, 300, 300, 200)        
        btn = QPushButton('Button', self)
        btn.move(100, 50)               
        btn.clicked.connect(self.btnPrint)
        self.comboBox = QComboBox(self)
        self.comboBox.setEditable(True)
        self.comboBox.move(100, 150)
        self.comboBox.setMinimumSize(QSize(150, 0))
        self.comboBox.setEditText("Initial Text")
        self.comboBox.editTextChanged.connect(self.cboxPrint)
        enter = QShortcut(QKeySequence(Qt.Key_Return), self)
        enter.activated.connect(self.returnDecision)
        self.textList = []
        self.show()

    def btnPrint(self):
        print("Button was pressed")

    def btnAction(self):
        print("RETURN pressed when NOT editing combo box")
        self.btnPrint()

    def cboxPrint(self):
        print(self.comboBox.currentText())

    def cboxAction(self):
        print("RETURN pressed when editing combo box")
        self.textList.append(self.comboBox.currentText())
        print(self.textList)        

    def returnDecision(self):
        if ENTER KEY WAS PRESSED WHILE EDITING COMBO BOX:
            self.cboxAction()
        else:
            self.btnAction()

if __name__ == '__main__':    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

有什么建议吗?在


Tags: fromimportselfreturndefconnectsyspyqt5
1条回答
网友
1楼 · 发布于 2024-05-16 05:17:23

解决这个问题的一种方法是使用QComboBox的自定义子类并重写keypresentevent方法。然后在小部件中实现一个keyPressEvent并以不同的方式处理每个事件。在

class CustomCombo(QtWidgets.QComboBox):

    enter_pressed = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Return:
            self.enter_pressed.emit()
        else:
            QtWidgets.QComboBox.keyPressEvent(self, event)  
            # if the key is not return, handle normally


class Example(QWidget):

    def __init__(self):
        # Code here
        self.combo_box = CustomCombo(self)
        self.combo_box.enter_pressed.connect(self.cboxAction)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Return:
            self.btnAction()

相关问题 更多 >