我的目标是在按 Enter 时向服务器发送消息。 下面我发布的解决方案每次按下按键时都有效,并且与哪个按键无关。我如何得到acctualy按下的键?
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()
答案 0 :(得分:0)
假设您使用auto-connection,只需将广告位的名称更改为:
def on_message_box_returnPressed(self):
...
这会使用returnPressed信号,但稍微更好的选择可能是使用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)