QAbstractTableModel中的data()到底执行几遍???

本文探讨了QAbstractTableModel中data()函数执行的次数问题。通过测试发现,data()函数实际上执行了3次,每次遍历都会为每一行每一项的七个角色赋值。问题源于QTableView的paintEvent()函数,该函数在绘制表格时调用data()。对于为何遍历三次的原因,文中提到可能与Qt内部的逻辑有关,但具体原因尚不明确。如果你知道其中原理,可以通过评论分享。
摘要由CSDN通过智能技术生成

有一个问题:QAbstractTableModel中的data()函数到底执行几遍???

 

 

发现问题的过程

 1、一个普通的继承 QAbstractTableModel 的类

 

 

class CurrencyModel : public QAbstractTableModel  
{  
public:  
    CurrencyModel(QObject *parent = 0);  
  
    void setCurrencyMap(const QMap<QString, double> &map);  
    int rowCount(const QModelIndex &parent) const;  
    int columnCount(const QModelIndex &parent) const;  
    QVariant data(const QModelIndex &index, int role) const;  
    QVariant headerData(int section, Qt::Orientation orientation,  
                        int role) const;  
  
private:  
    QString currencyAt(int offset) const;  
  
    QMap<QString, double> currencyMap;  
};  

 

 

 2、其中的重载的data()函数如下:

 

//返回一个项的任意角色的值,这个项被指定为QModelIndex
QVariant MoReconQueue::data(const QModelIndex &index, int role) const
{
	qDebug() <<"role:"<< role<< "index : " << index.row() << index.column();
    //模型索引无效,返回空值
    if (!index.isValid())
        return QVariant();
    //对其角色
    if (role == Qt::TextAlignmentRole)
    {
        return int(Qt::AlignRight | Qt::AlignVCenter);
    }
    //显示角色
    else if (role == Qt::DisplayRole)
    {
		
        return reconQueueAt(index.row(),index.column());

    }
	
    //返回空值
    return QVariant();
}
 

 

3、测试结果:

发现data()执行了3次遍历,每次遍历都执行每一行每一项的七个角色的赋值。

 

 

role: 6 index :  0 0

role: 7 index :  0 0

role: 9 index :  0 0

role: 10 index :  0 0

role: 1 index :  0 0

role: 0 index :  0 0

role: 8 index :  0 0 

 

 

 

 

我就纳闷了,执行一次遍历就够了,为啥要执行三遍呢。

 

Qt项数据角色如下:

 

enum Qt::ItemDataRole

Each item in the model has a set of data elements associated with it, each with its own role. The roles are used by the view to indicate to the model which type of data it needs. Custom models should return data in these types.

The general purpose roles (and the associated types) are:

Constant Value Description
Qt::DisplayRole 0 The key data to be rendered in the form of text. (QString)
Qt::DecorationRole 1 The data to be rendered as a decoration in the form of an icon. (QColorQIcon or QPixmap)
Qt::EditRole 2 The data in a form suitable for editing in an editor. (QString)
Qt::ToolTipRole 3 The data displayed in the item's tooltip. (
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值