10.model/view实例(2)

任务:显示一个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();
}

 

转载于:https://www.cnblogs.com/billxyd/p/6917091.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值