Bound channel row painting and support pixel-sized fonts

This commit is contained in:
evgeny committed 2026-10-27 10:51:20 +01:00
1 parent dea94d01d8
commit 19abd46f07
2 files changed
+39 -27

No files matched your search

+20 -14
View File
@@ -1,13 +1,17 @@
#include "channeldelegate.h"
#include "debug_ui.h"
#include <QPainter>
#include <QApplication>
ChannelDelegate::ChannelDelegate(QObject *parent)
: QStyledItemDelegate(parent) {}
: QStyledItemDelegate(parent) {
DEBUG_DEBUG(DEBUG_CATEGORY_CHAT, "ChannelDelegate created: row=56 avatar=32 bounded single-line preview");
}
void ChannelDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const {
painter->save();
painter->setClipRect(option.rect, Qt::IntersectClip);
/* ── заголовок секции (например, «Личные») ── */
if (index.data(ChannelIsSectionRole).toBool()) {
@@ -78,13 +82,14 @@ void ChannelDelegate::paint(QPainter *painter, const QStyleOptionViewItem &optio
}
QRect textRect(iconRect.right() + margin, option.rect.top() + margin,
option.rect.right() - iconRect.right() - 2 * margin,
option.rect.height() - 2 * margin);
qMax(0, option.rect.right() - iconRect.right() - 2 * margin),
qMax(0, option.rect.height() - 2 * margin));
QString name = index.data(ChannelNameRole).toString();
QFont nameFont = option.font;
nameFont.setBold(true);
nameFont.setPointSize(nameFont.pointSize() + 1);
if (nameFont.pointSizeF() > 0) nameFont.setPointSizeF(nameFont.pointSizeF() + 1);
else nameFont.setPixelSize(nameFont.pixelSize() + 1);
painter->setFont(nameFont);
QColor textColor = (option.state & QStyle::State_Selected)
@@ -98,14 +103,15 @@ void ChannelDelegate::paint(QPainter *painter, const QStyleOptionViewItem &optio
QString unreadText = unread > 99 ? QStringLiteral("99+") : QString::number(unread);
QFont unreadFont = option.font; unreadFont.setBold(true); unreadFont.setPixelSize(11);
int unreadWidth = qMax(18, QFontMetrics(unreadFont).horizontalAdvance(unreadText) + 8);
if (unread > 0) nameRect.setRight(nameRect.right() - unreadWidth - 6);
painter->drawText(nameRect, Qt::AlignLeft | Qt::AlignTop,
if (unread > 0) nameRect.setWidth(qMax(0, nameRect.width() - unreadWidth - 6));
painter->drawText(nameRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine,
painter->fontMetrics().elidedText(name, Qt::ElideRight, nameRect.width()));
QString lastMsg = index.data(ChannelLastMessageRole).toString();
if (!lastMsg.isEmpty()) {
if (!lastMsg.isEmpty() && textRect.width() > 0) {
QFont msgFont = option.font;
msgFont.setPointSize(msgFont.pointSize() - 1);
if (msgFont.pointSizeF() > 0) msgFont.setPointSizeF(qMax(1.0, msgFont.pointSizeF() - 1));
else msgFont.setPixelSize(qMax(1, msgFont.pixelSize() - 1));
QColor nickColor(0x33, 0x90, 0xEC);
QColor msgColor = (option.state & QStyle::State_Selected)
? option.palette.highlightedText().color().darker(120)
@@ -114,30 +120,30 @@ void ChannelDelegate::paint(QPainter *painter, const QStyleOptionViewItem &optio
QRect msgRect(textRect.left(), nameRect.bottom() + 4,
textRect.width(),
option.rect.bottom() - nameRect.bottom() - margin);
qMax(0, option.rect.bottom() - nameRect.bottom() - margin));
QFontMetrics msgFm(msgFont);
int colon = lastMsg.indexOf(QString::fromUtf8(": "));
if (colon >= 0) {
QString nick = lastMsg.left(colon + 1);
QString nick = msgFm.elidedText(lastMsg.left(colon + 1), Qt::ElideRight, msgRect.width());
QString body = lastMsg.mid(colon + 2);
painter->setFont(msgFont);
painter->setPen(nickColor);
QRect nickRect = msgRect;
nickRect.setWidth(msgFm.horizontalAdvance(nick));
painter->drawText(nickRect, Qt::AlignLeft | Qt::AlignTop, nick);
nickRect.setWidth(qMin(msgRect.width(), msgFm.horizontalAdvance(nick)));
painter->drawText(nickRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, nick);
painter->setPen(msgColor);
QRect bodyRect(msgRect.left() + nickRect.width(), msgRect.top(),
msgRect.width() - nickRect.width(), msgRect.height());
QString elidedBody = msgFm.elidedText(body, Qt::ElideRight, bodyRect.width());
painter->drawText(bodyRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, elidedBody);
painter->drawText(bodyRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, elidedBody);
} else {
painter->setFont(msgFont);
painter->setPen(msgColor);
QString elided = msgFm.elidedText(lastMsg, Qt::ElideRight, msgRect.width());
painter->drawText(msgRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, elided);
painter->drawText(msgRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, elided);
}
}
+19 -13
View File
@@ -1,30 +1,36 @@
/* Роли модели и отрисовка ChannelList: канал/PM, последнее сообщение и unread. */
/* Роли плоской модели ChannelList и её делегат; использовать только в GUI-потоке.
* Установить через QListView::setItemDelegate(), QObject-parent владеет делегатом.
* Строка канала/PM: аватар, состояние связи, название, одна строка последнего сообщения и unread.
* Заголовок секции рисуется без этих индикаторов; запрет выбора задаётся flags модели.
* Всё рисование ограничено option.rect и сохраняет исходное состояние QPainter. */
#pragma once
#include <QStyledItemDelegate>
enum ChannelDataRole {
ChannelNameRole = Qt::DisplayRole,
ChannelIconRole = Qt::DecorationRole,
ChannelLastMessageRole = Qt::UserRole + 1,
ChannelChannelIdRole = Qt::UserRole + 2,
ChannelPeersOnlineRole = Qt::UserRole + 3, /* int: count of online peers */
ChannelAutoConnectActiveRole = Qt::UserRole + 4, /* bool: 1 if auto-connect in progress */
ChannelUnreadCountRole = Qt::UserRole + 6, /* int: unread message count, 0 if none */
ChannelLastMsgAtRole = Qt::UserRole + 7, /* qint64: last message timestamp for sorting */
ChannelDmOnlineRole = Qt::UserRole + 11, /* bool: живой BGP-путь PM */
ChannelDmGenerationRole = Qt::UserRole + 12, /* quint64: поколение видимой истории PM */
ChannelIsSectionRole = Qt::UserRole + 10 /* bool: 1 = заголовок секции (не выбирается) */
ChannelNameRole = Qt::DisplayRole, /* QString: название/имя собеседника/заголовок секции. */
ChannelIconRole = Qt::DecorationRole, /* QIcon: аватар, область 32×32. */
ChannelLastMessageRole = Qt::UserRole + 1, /* QString: превью; первая ": " отделяет цветное имя автора. */
ChannelChannelIdRole = Qt::UserRole + 2, /* QString: ID канала или "dm:<conv_id>" для PM. */
ChannelPeersOnlineRole = Qt::UserRole + 3, /* int >= 0: зелёная полоса и счётчик онлайн-пиров, максимум "9+". */
ChannelAutoConnectActiveRole = Qt::UserRole + 4, /* bool: жёлтая полоса, если нет онлайн-пиров. */
ChannelUnreadCountRole = Qt::UserRole + 6, /* int >= 0: непрочитанные; 0 скрывает значок, максимум "99+". */
ChannelLastMsgAtRole = Qt::UserRole + 7, /* qint64: timestamp для списка, делегат его не рисует. */
ChannelDmOnlineRole = Qt::UserRole + 11, /* bool: зелёная/красная точка PM по наличию живого BGP-пути. */
ChannelDmGenerationRole = Qt::UserRole + 12, /* quint64: поколение истории PM для списка, не рисуется. */
ChannelIsSectionRole = Qt::UserRole + 10 /* bool: рисовать только название секции на фоне window. */
};
class ChannelDelegate : public QStyledItemDelegate {
Q_OBJECT
public:
/* Создаёт делегат; parent необязателен, без него освобождает вызывающий. */
explicit ChannelDelegate(QObject *parent = nullptr);
/* Рисует роли index в option.rect активным заимствованным painter, учитывая выбор/hover и палитру. */
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
/* Возвращает 200×56 для всех строк, включая секции; view задаёт фактическую ширину. */
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
};