打造PyQt5微信风格聊天界面:气泡消息显示
本文介绍如何使用PyQt5构建一个类似微信的聊天界面,并实现气泡样式的消息显示效果。
核心思路是利用QListWidget作为聊天窗口,将每个聊天消息项目提升为QWidget,从而实现自定义气泡形状和样式。
代码示例:
import sysimport randomfrom PyQt5 import QtCore, QtGui, QtWidgetsclass ChatItem(QtWidgets.QWidget): User_Me = 0 User_Other = 1 User_System = 2 def __init__(self, text, time, user_type, parent=None): super(ChatItem, self).__init__(parent) self.text = text self.time = time self.user_type = user_type self.setupUI() def setupUI(self): self.setFixedSize(self.calculateSize()) mainLayout = QtWidgets.QVBoxLayout() mainLayout.setContentsMargins(0, 0, 0, 0) self.setLayout(mainLayout) self.textLabel = QtWidgets.QLabel(self.text) self.textLabel.setWordWrap(True) self.textLabel.setStyleSheet(self.getStyle()) # 应用样式 mainLayout.addWidget(self.textLabel) self.timeLabel = QtWidgets.QLabel(self.time) self.timeLabel.setAlignment(QtCore.Qt.AlignRight) mainLayout.addWidget(self.timeLabel) def calculateSize(self): fm = QtGui.QFontMetrics(self.textLabel.font()) textWidth = fm.boundingRect(self.text).width() + 10 textHeight = fm.boundingRect(self.text).height() + 10 width = max(textWidth, 40) # 最小宽度40 height = max(textHeight, 20) # 最小高度20 return QtCore.QSize(width, height) def getStyle(self): if self.user_type == ChatItem.User_Me: return "background-color: rgb(173, 216, 230); border-radius: 10px; padding: 5px;" elif self.user_type == ChatItem.User_Other: return "background-color: rgb(220, 248, 198); border-radius: 10px; padding: 5px;" else: # System return "background-color: rgb(240, 240, 240); border-radius: 10px; padding: 5px; color: gray;"class ChatWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(ChatWindow, self).__init__(parent) self.chatWidget = QtWidgets.QListWidget() self.chatWidget.setSpacing(0) self.setCentralWidget(self.chatWidget) def addItem(self, text, time, user_type): item = QtWidgets.QListWidgetItem() chatItem = ChatItem(text, time, user_type) self.chatWidget.addItem(item) item.setSizeHint(chatItem.sizeHint()) self.chatWidget.setItemWidget(item, chatItem)if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = ChatWindow() window.show() userTypes = [ChatItem.User_Me, ChatItem.User_Other, ChatItem.User_System] for i in range(15): userType = random.choice(userTypes) time = QtCore.QDateTime.currentDateTime().toString("hh:mm") text = "Message from " + ["Me", "Other", "System"][userType] window.addItem(text, time, userType) sys.exit(app.exec_())
登录后复制
气泡样式:
代码中通过getStyle()方法根据用户类型设置不同的样式:
自己发送的消息(User_Me):蓝色气泡背景。对方发送的消息(User_Other):绿色气泡背景。系统消息(User_System):灰色气泡背景,文字颜色为灰色。
这个例子提供了一个基础的框架,您可以根据需要进一步完善,例如添加头像、表情、文件传输等功能,以及更精细的气泡样式定制。 记得安装PyQt5: pip install PyQt5
以上就是如何用PyQt5创建具有气泡效果的仿微信聊天界面?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2168330.html