方法一:代理
新建一个代理类,重写paint函数:
class CommonDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
CommonDelegate();
private:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
CommonDelegate::CommonDelegate()
{
}
void CommonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem itemOption(option);
if(itemOption.state&QStyle::State_HasFocus)
{
itemOption.state=itemOption.state^QStyle::State_HasFocus;
}
if(3==index.column())
{
QPixmap pix;
if(QString("结案")==index.data().toString())
pix.load(":/Resources/check.png");
else if(QString("激活")==index.data().toString())
pix.load(":/Resources/active.png");
QRect rect=option.rect;
rect.adjust(0,6,0,0);
rect.setSize(QSize(20,20));
pix.scaled(20,20,Qt::KeepAspectRatio);
painter->setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform);
painter->drawPixmap(rect,pix);
}
QStyledItemDelegate::paint(painter,itemOption,index);
}
TableView设置:
this->setItemDelegate(new CommonDelegate());
效果:
图标和文字重叠,且点击后看不到图标,这不是我想要的效果。
方法二:重写Model
继承QSqlQueryModel(一般使用QSqlTableModel即可),重写data函数
class SqlTableModel : public QSqlQueryModel
{
Q_OBJECT
public:
explicit SqlTableModel(QObject *parent=0);
~SqlTableModel();
QVariant data(const QModelIndex &idx, int role) const;
};
QVariant SqlTableModel::data(const QModelIndex &idx, int role) const
{
QVariant value=QSqlQueryModel::data(idx,role);
if(3==idx.column()&&Qt::DecorationRole==role)
{
QString PNType=idx.data().toString();
if(QString("结案")==PNType)
{
return QIcon(":/Resources/check.png");
}
else if(QString("激活")==PNType)
{
return QIcon(":/Resources/active.png");
}
}
return value;
}
效果:
部分效果需要使用QSS:
QTableView{
font-family:"Microsoft Yahei";
font-size:10pt;
color: rgb(26,52,93);
selection-color: black;
selection-background-color: rgb(255,209,128);
border: 0px;
border-top: 1px solid lightgray;
}
更多QSS使用方法,在Qt Assistant中搜索stylesheet
,在Qt Style Sheets Examples 中查看。
评论区