要实现气泡聊天界面,你可以使用 Qt 的 QListView 和自定义的委托类来完成。下面是一个简单的示例代码:
#include <QApplication>
#include <QListView>
#include <QStandardItemModel>
#include <QStyledItemDelegate>
#include <QPainter>
class BubbleDelegate : public QStyledItemDelegate {
public:
explicit BubbleDelegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) {}
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override {
QString text = index.data(Qt::DisplayRole).toString();
bool isRightBubble = index.data(Qt::UserRole).toBool();
// 设置字体和颜色
QFont font = option.font;
QColor textColor = option.palette.text().color();
if (isRightBubble)
textColor = QColor(255, 255, 255); // 右侧气泡文字颜色为白色
// 绘制气泡背景
QRect bubbleRect = option.rect.adjusted(2, 2, -2, -2);
if (isRightBubble)
painter->setBrush(QColor(0, 120, 215)); // 右侧气泡背景颜色为蓝色
else
painter->setBrush(QColor(225, 225, 225)); // 左侧气泡背景颜色为灰色
painter->drawRoundedRect(bubbleRect, 10, 10);
// 绘制文字内容
painter->setFont(font);
painter->setPen(textColor);
QRect textRect = bubbleRect.adjusted(10, 10, -10, -10);
painter->drawText(textRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, text);
}
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override {
QString text = index.data(Qt::DisplayRole).toString();
QFontMetrics metrics(option.font);
QRect boundingRect = metrics.boundingRect(QRect(0, 0, 300, 0), Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, text);
return QSize(boundingRect.width() + 20, boundingRect.height() + 20); // 调整大小以适应内容
}
};
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
QListView listView;
QStandardItemModel model;
BubbleDelegate delegate;
listView.setModel(&model);
listView.setItemDelegate(&delegate);
// 添加左侧气泡项
QList<QStandardItem*> leftItems;
leftItems.append(new QStandardItem("Hello!"));
leftItems.last()->setData(false, Qt::UserRole); // 左侧气泡标记为 false
model.appendRow(leftItems);
// 添加右侧气泡项
QList<QStandardItem*> rightItems;
rightItems.append(new QStandardItem("Hi there!"));
rightItems.last()->setData(true, Qt::UserRole); // 右侧气泡标记为 true
model.appendRow(rightItems);
listView.show();
return app.exec();
}
在上面的示例中,我们通过自定义委托类 BubbleDelegate
来绘制每个气泡消息的背景和文本内容。在 paint
函数中,我们使用 QPainter 对象进行绘制操作,根据消息类型设置不同的背景颜色和文字颜色。通过 sizeHint
函数可以自动调整气泡项的大小以适应内容。
这只是一个简单的示例,你可以根据需要进行进一步的定制和美化。希望对你有所帮助!
内容由零声教学AI助手提供,问题来源于学员提问