1. 程式人生 > >10.model/view實例(2)

10.model/view實例(2)

code == splay stat 根據 表格 例子 修改 顯示

任務:顯示一個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實例(2)