From 35570a7cb46556355ce074812fe8b112c3082a8b Mon Sep 17 00:00:00 2001 From: Krad Date: Wed, 8 Dec 2021 17:49:11 +0800 Subject: [PATCH] A better display item replace method --- src/components/AccountRoleComboDelegate.cpp | 13 +++++++++---- src/components/AccountRoleComboDelegate.h | 7 ++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/components/AccountRoleComboDelegate.cpp b/src/components/AccountRoleComboDelegate.cpp index 8929a76..17c518c 100644 --- a/src/components/AccountRoleComboDelegate.cpp +++ b/src/components/AccountRoleComboDelegate.cpp @@ -5,15 +5,20 @@ #include "AccountRoleComboDelegate.h" #include #include +#include #include "db/SQLHelper.h" AccountRoleComboDelegate::AccountRoleComboDelegate(QWidget *parent):QItemDelegate(parent) { SQLHelper::QueryMap("select RoleID,RoleName from Role",map); } +//之前使用重写paint来实现了替换显示文字,效果一般 +// +//void AccountRoleComboDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { +// QItemDelegate::paint(painter, option, index); +//} -void AccountRoleComboDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - - QString text = index.model()->data(index, Qt::DisplayRole).toString(); - +//相较于直接在paint里面操作,这是一个更好的选择,可以直接改变Display,而不影响前后景的绘制。 +void AccountRoleComboDelegate::drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, + const QString &text) const { //绘制文本 painter->drawText(option.rect, Qt::TextWordWrap | Qt::AlignCenter , map[text].toString()); } diff --git a/src/components/AccountRoleComboDelegate.h b/src/components/AccountRoleComboDelegate.h index f533453..8e38b8a 100644 --- a/src/components/AccountRoleComboDelegate.h +++ b/src/components/AccountRoleComboDelegate.h @@ -12,9 +12,10 @@ class AccountRoleComboDelegate:public QItemDelegate { Q_OBJECT public: explicit AccountRoleComboDelegate(QWidget *parent = nullptr); - void paint(QPainter *painter, - const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + +protected: + void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, + const QRect &rect, const QString &text) const override ; private: QAbstractItemModel* model = nullptr; QMap map ;