简体   繁体   English

使用PyQt创建一个简单的聊天界面

[英]Creating a simple chat Interface using PyQt

Am currently creating a simple chat application that looks like a usual messaging service. 我当前正在创建一个看起来像普通消息传递服务的简单聊天应用程序。 the problem am facing is that Ive failed to add more QLabels on a QVBoxLayout by just pressing the send button. 面临的问题是我仅通过按发送按钮就无法在QVBoxLayout上添加更多QLabel。 All it does is send the message to the layout as expected but when i send another message, instead of appending, it replaces the first message. 它所做的只是按预期方式将消息发送到布局,但是当我发送另一条消息而不是追加时,它将替换第一条消息。 The following code is run when the send button is clicked. 单击发送按钮时,将运行以下代码。

self.message = QtGui.QLabel()
# self.messageField is the QTextEdit where the user writes the message
text = self.messageField.toPlainText()
self.message.setText(text)
self.messageField.clear()
# self.messageLayout is our QVBoxLayout
self.messageLayout.addWidget(self.message)
self.messageLayout.setAlignment(self.message, QtCore.Qt.AlignTop)
# self.widget is on top od the QScrollArea and it holds the QVBoxLayout
self.widget.setLayoutDirection(QtCore.Qt.RightToLeft)
self.widget.setLayout(self.messageLayout)

I don't know where the problem lays 我不知道问题出在哪里

self.message = QtGui.QLabel() replaces the first QLabel reference stored as an instance attribute. self.message = QtGui.QLabel()替换了作为实例属性存储的第一个QLabel引用。

Try to implement a list instead, to store all messages from the beginning. 尝试实现一个列表,从头开始存储所有消息。

You need to add this before, in the __init__ method : 您需要在__init__方法中添加它:

self.messages = []

And in the method triggered by the button : 并在按钮触发的方法中:

message = QtGui.QLabel()

text = self.messageField.toPlainText()
message.setText(text)
self.messageField.clear()
self.messageLayout.addWidget(message)
self.widget.setLayoutDirection(QtCore.Qt.RightToLeft)
self.widget.setLayout(self.messageLayout)
# and to keep a direct reference :
self.messages.append(message)

EDIT : 编辑:

You may need to define alignment only once at beginning, just after you define your layout, that might fix the centered message issue : 您可能只需要在开始定义布局后就定义一次对齐,这可以解决居中消息问题:

self.messageLayout = QVBoxLayout() # (i assume...)
self.messageLayout.setAlignment(QtCore.Qt.AlignTop)

and i think you should do the same for these 2 lines, no need to repeat this each time you append a message to the list : 而且我认为您应该对这两行进行相同的操作,无需在每次向列表中添加一条消息时重复此操作:

self.widget.setLayoutDirection(QtCore.Qt.RightToLeft)
self.widget.setLayout(self.messageLayout)`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM