处理在 QLineEdit 中按下的键,哪个实例在 QMainWindow 中

Handling key pressed in QLineEdit which instance is in QMainWindow

我的目标是在按 Enter 时向服务器发送消息。 下面我 post 解决方案,每次按下键时都有效,而不管它是哪个键。我怎样才能得到准确按下的键?

from sys import argv, exit

from interface import Ui_MainWindow
from PyQt5.QtGui import QKeyEvent
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import QApplication, QMainWindow
from client import connect_to_server, send_message


class Communicator(QMainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    @pyqtSlot()
    def on_message_box_textChanged(self):
        server_socket = connect_to_server()
        message = self.ui.message_box.toPlainText()
        send_message(message, server_socket)


def main():
    main_application = QApplication(argv)
    window = Communicator()
    window.show()
    exit(main_application.exec_())

if __name__ == '__main__':
    main()

假设您使用的是 auto-connection,您只需将插槽名称更改为:

    def on_message_box_returnPressed(self):
        ...

这使用 returnPressed signal, but a slightly better choice might be to use the editingFinished 信号:

    def on_message_box_editingFinished(self):
        ...

使用 显式 信号连接,您的代码将如下所示:

class Communicator(QMainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.message_box.editingFinished.connect(self.sendMessage)

    def sendMessage(self):
        server_socket = connect_to_server()
        message = self.ui.message_box.toPlainText()
        send_message(message, server_socket)