如何设置QSqlQueryModel的Qt::Vertical headerData在进行分页时增加数字

How to set Qt::Vertical headerData of QSqlQueryModel increasing numbers when doing pagination

本文关键字:分页 数字 增加数 增加 headerData Vertical 设置 QSqlQueryModel Qt 何设置      更新时间:2023-10-16

im使用从限制查询中选择的QSqlQueryModel进行简单分页
一切都很顺利。但是现在我喜欢反映QTableView的垂直头数据
在实现headerData时,由于它是const函数,我无法在其中进行任何计算。所以我在计算垂直标题中的正确数字时遇到了问题。例如,im获取从20到30的行
我喜欢竖排显示数字20到30。等等
这就是我实现headerData:的方式

QVariant PlayListSqlModel::headerData(int section, Qt::Orientation orientation, int role) const 
{
    if(orientation == Qt::Vertical && role == Qt::DisplayRole)
    {
        return section;
    }
    if (role == Qt::DisplayRole)
    {
        if (orientation == Qt::Horizontal) {
            switch (section)
            {
            case 0:
                return QString("name");
            case 1:
                return QString("From");
            case 2:
                return QString("Created Time");
            case 3:
                return QString("last name");
            case 4:
            }
        }
    }
    return QVariant();
}

更新:
我甚至试着调用const函数来进行计算,但我在新的const函数上仍然存在编译错误:错误C2166:l-value指定常量对象

int PlayListSqlModel::calculateVerticalHeader()  const 
{
    int returnHeaderCount = m_iHeaderCount;
    m_iHeaderCount++;
    return returnHeaderCount;
}

QVariant PlayListSqlModel::headerData(int section, Qt::Orientation orientation, int role) const 
{
    if(orientation == Qt::Vertical && role == Qt::DisplayRole)
    {
        return calculateVerticalHeader();
    }
    if (role == Qt::DisplayRole)
    {
        if (orientation == Qt::Horizontal) {
            switch (section)
            {
            case 0:
                return QString("Clip");
            case 1:
                return QString("From");
            case 2:
                return QString("Created Time");
            case 3:
                return QString("Rating");
            case 4:
                return QString("Feed");
            case 5:
                return QString("Double click to watch");
            }
        }
    }
    return QVariant();
}

只要有一个包含当前页面的可访问成员变量,就可以简单地将其乘以每页+行的行数。

  if(orientation == Qt::Vertical && role == Qt::DisplayRole)
    {
        return QString("%1").arg(m_currentPage*m_rowsPerPage+section);
    }

但正如Alxx所说,你认为你不能进行任何计算,可能是因为你没有调用返回我在上例中使用的变量的非常数方法,对吧?

更新得到错误C2166:l-value指定const对象的原因是,您试图增加类变量:m_iHeaderCount++,这在const声明的方法中是不允许的。您可以在headerData方法中修改局部变量,但不能修改类变量。

>> beacose这是const函数,我不能在里面进行任何计算
您对C++中的const有一些奇怪的理解。Const函数不能修改this对象或调用非Const函数,仅此而已。您的模型知道当前页面和页面大小,不是吗?如果是,它可以计算行号。如果像currentPage()rowCount()这样的实用程序函数(或其他任何函数)是非常量的,请将它们标记为"是"。无论如何,这都是很好的做法。

您已经在做必要的检查了。section变量告诉需要处理哪一行(如果orientarionQt::Vertical)。如果您只想返回行的一个数字,您可以只返回QVariant(QString::number(section))