使用QStandardItemModel作为QTableView的model,想要设置各行背景颜色,没有现成的方法,最简单的做法就是自己封装一个model类继承QStandardItemModel,重新实现data方法。
mymodel.h
#ifndef MYMODEL_H
#define MYMODEL_H
#include <QVariant>
#include <QStandardItemModel>
class MyModel : public QStandardItemModel
{
public:
MyModel();
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
};
#endif // MYMODEL_H
mymodel..cpp
#include "mymodel.h"
#include <QDebug>
MyModel::MyModel()
{
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::TextAlignmentRole)
{
return int(Qt::AlignLeft | Qt::AlignVCenter);
}
else if (role == Qt::DisplayRole)
{
return QStandardItemModel::data(index, role);
}
else if(role == Qt::BackgroundColorRole )
{
if(index.row()%5 == 0)
return QColor(Qt::red);
else if(index.row()%5 == 1)
return QColor(Qt::green);
else if(index.row()%5 == 2)
return QColor(Qt::blue);
else if(index.row()%5 == 3)
return QColor(Qt::yellow);
else if(index.row()%5 == 4)
return QColor(Qt::gray);
else
return QVariant();
}
return QVariant();
return QVariant();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStandardItemModel>
#include <QString>
#include "mymodel.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
MyModel *model = new MyModel();
model->setColumnCount(2);
model->setHeaderData(0,Qt::Horizontal,tr("货品名称"));
model->setHeaderData(1,Qt::Horizontal,tr("货品类型"));
ui->tableView->setModel(model);
ui->tableView->setColumnWidth(0,100);
ui->tableView->setColumnWidth(1,100);
for (int i=0;i<1;i++){
if(i%2!=0)
{
model->setItem(i,0,new QStandardItem("ddd"));
model->setItem(i,1,new QStandardItem("哈哈"));
// model->data(model->index(i,1),Qt::BackgroundRole);//使用此方法也能改变背景色,但是只能改变某个item无法改变一整行?
}
else{
model->setItem(i,0,new QStandardItem("ddd"));
model->setItem(i,1,new QStandardItem("哈哈"));
}
}
}
MainWindow::~MainWindow()
{
delete ui;
}
实现效果如下图