10.model/view实例

Posted billxyd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了10.model/view实例相关的知识,希望对你有一定的参考价值。

任务:显示一个2x3的表格,将表格中的数据显示如下:

    

 

 

思考:

1.如何显示数据和上个例子一样。

2.但是每个单元格的数据都是有角色划分的。 Qt::ItemDataRole

3.View从Model中获取数据,通过data函数。每一个单元格根据角色,调用多次data函数。个人理解:单元格什么角色都调用一次data函数。

 

代码如下:就是修改data函数的代码。

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    int row = index.row();
    int col = index.column();

    if(role == Qt::DisplayRole) {
        if(row == 0 && col == 0)
            return QString ("Row%1,Column%2").arg(index.row()+1).arg(index.column()+1);
        if(row == 0 && col == 2)
            return QString ("Row%1,Column%2").arg(index.row()+1).arg(index.column()+1);
        if(row == 1 && col == 0)
            return QString ("Row%1,Column%2").arg(index.row()+1).arg(index.column()+1);
        if(row == 1 && col == 2)
            return QString ("Row%1,Column%2").arg(index.row()+1).arg(index.column()+1);
        if(row == 0 && col == 1)
            return QString ("<--left");
        if(row == 1 && col == 1)
            return QString ("right-->");
    }

    if(role == Qt::FontRole) {
        if(row == 0 && col == 0) {
            QFont bold;
            bold.setBold(true);
            return bold;
        }
    }

    if(role == Qt::TextAlignmentRole) {
        if(row == 0 && col == 1)
            return Qt::AlignLeft + Qt::AlignVCenter;
        if(row == 1 && col == 1)
            return Qt::AlignRight + Qt::AlignVCenter;
    }

    if(role == Qt::BackgroundColorRole) {
        if(row == 1 && col == 2)
            return Qt::red;
    }

    if(role == Qt::CheckStateRole) {
        if(row == 1 && col == 0)
            return Qt::Checked;
    }

    return QVariant();
}

 

以上是关于10.model/view实例的主要内容,如果未能解决你的问题,请参考以下文章