QTableWidgetItem子类运算符<()在对QTableWidget进行排序时从未被调用

QTableWidgetItem subclass operator<() never getting called when sorting QTableWidget

本文关键字:排序 调用 QTableWidget 在对 运算符 子类 lt QTableWidgetItem      更新时间:2023-10-16

我想为QTableWidget实现一个自定义排序,所以我将QTableWidgetItem子类化,并重新实现了operator<()函数。

class FloatFieldTableItem : public QTableWidgetItem
{
public:
    FloatFieldTableItem(qreal theFloat) :
    QTableWidgetItem(),
    _float(theFloat)
    {}
    virtual bool operator<(FloatFieldTableItem const &other) const
    {
        return _float < other.float;
    }
private:
    qreal _float;
};

但由于某种原因,operator<()函数从未被调用!

tableWidget->setItem(0, 0, new FloatFieldTableItem(0.1));
tableWidget->setItem(1, 0, new FloatFieldTableItem(0.3));
tableWidget->setItem(2, 0, new FloatFieldTableItem(6.1));
// This should result in a call to the operator<() function above
tableWidget->sortItems(0);

您的operator<()的签名与QTableWidgetItem的签名不匹配,因此即使它已被声明为虚拟的,它也不会以允许QTableWidget调用它的方式进入vtable

签名QTableWidgetItemoperator<()QTableWidgetItem作为参数,因此您必须将其强制转换为FloatFieldTableItem才能执行您想要的操作。

virtual bool operator<(QTableWidgetItem const &other) const
{
    FloatFieldTableItem const *item
        = dynamic_cast<FloatFieldTableItem const*>(&other);
    if(item)
    {
        return _float < item->_float;
    }
    else
    {
        return QTableWidgetItem::operator<(other);
    }
}