前面讲解了有关Model/View的实现方式,下面将用一个例子,介绍如何构造model和使用Delegate渲染进行混合编程,主要显示学生信息,tableview里面有checkbox, combBox, lineEdit等操作控件,最终效果如下。
1.首先,我们建立2个学生的基本信息(姓名,性别,年龄,分数,是否毕业),并放在链表中。姓名不可编辑,性别combox下拉可选,年龄,分数双击可修改,是否毕业开关可编辑。
enum E_Gender
{
E_BOY,
E_GIRL,
};
typedef struct S_Student
{
bool m_check;
QString m_name;
int m_age;
E_Gender m_gender;
int m_score;
bool m_graduate;
}S_STU;
QList<S_STU*> StuList;
StuList.clear();
S_STU *stu1 = new S_STU;
stu1->m_check = false;
stu1->m_name = QString("XiaoMing");
stu1->m_gender = E_BOY;
stu1->m_age = 12;
stu1->m_score = 98;
stu1->m_graduate = true;
S_STU *stu2 = new S_STU;
stu2->m_check = false;
stu2->m_name = QString("XiaoHong");
stu2->m_gender = E_GIRL;
stu2->m_age = 10;
stu2->m_score = 100;
stu2->m_graduate = false;
StuList.append(stu1);
StuList.append(stu2);
2.构造model模型,重载常用的虚函数。
int StudentModel::columnCount(const QModelIndex & parent) const
{
Q_UNUSED(parent);
return 6;
}
int StudentModel::rowCount(const QModelIndex & parent) const
{
Q_UNUSED(parent);
return StuList.count();
}
QVariant StudentModel::data(const QModelIndex & index, int role) const
{
if (!index.isValid())
return QVariant();
int nRow = index.row();
int nColumn = index.column();
S_STU *stu = StuList.at(nRow);
switch(role){
case Qt::TextColorRole:
return QColor(Qt::black);
case Qt::TextAlignmentRole:
return QVariant(Qt::AlignHCenter | Qt::AlignVCenter);
case Qt::UserRole+COLUMN_CHECK:
{
if (nColumn == COLUMN_CHECK)
return stu->m_check;
return "";
}
case Qt::DisplayRole:
{
if (nColumn == COLUMN_NAME)