QT ⾃定义QTableView 的排序⽅式
1、通常情况下,我们都是对QTableView的Item的text进⾏排序的(Qt::DisplayRole),实际上还可以对其他内容进⾏排序(参考enum Qt::ItemDataRole)
2、默认情况下,Item的排序是按照字符串的⽅式来排序的,这就是为什么我们看到排序结果类似于: ("100","20","3","400")。一寸阳光
3、通过追看QT(4.6.1)的源代码,发现QTableView的排序函数sortByColumn根源在,但其中的排序函数什么都没做,实际上还是在"QStandardItemModel::sort(int column, Qt::SortOrder order)"中实现的,排序函数有依赖于 "bool QStandardItem::operator<(const QStandardItem &other) const"。上⾯引号中内容都在"/qt-everywhere-opensource-src-4.6.1/src/gui/itemviewsqstandarditemmodel.cpp"中。
如下:卡丁车技巧>腊肉炒春笋
/a other; otherwi
returns fal.
item's sort role (e
QStandardItemMod
el::sortRole) to perform the
comparison if the
如何查看手机型号
item belongs to a
model; otherwi,
the data for the
item's
Qt::DisplayRole
(text()) is ud to
嘉实多磁护
perform the
comparison.
sortChildren()
and
QStandardItemMod
el::sort() u this
function when
sorting items. If
you want custom
sorting, you can
subclass
QStandardItem
and reimplement
this function.
*/
蒙太奇硅藻泥
bool
QStandardItem::ope
rator<(const
QStandardItem
&other) const
{
const int role =
model() ? model()-
>sortRole() :
Qt::DisplayRole;
const QVariant l =
data(role), r =
other.data(role);
// this code is
copied from
QSortFilterProxyMo
del::lessThan()
switch
十年春
(l.urType()) {
ca
QVariant::Invalid:
return (r.type()
==
QVariant::Invalid);
ca QVariant::Int: Int() <
QVariant::UInt:
UInt()
< r.toUInt();
ca
QVariant::LongLong:
return
药用价值
{public: QuoteItem(){} QuoteItem(const QString &text) :QStandardItem(tex t) { } QuoteItem(const QuoteItem &other) : QStandardItem(oth
er) { } QuoteItem &operator=(const QuoteItem &other) { QStandardItem::ope rator=(other); return *this; } virtual bool operator<(const QStandardItem &other) const { const QVariant l = data(Qt::DisplayRole ), r = other.data(Qt::Displ ayRole); if (column() == lumn() && lumn() >= 1 && lumn() <= 15) { Double() < r.toDouble(); } return QStandardItem::ope rator<(other); }};我的⽬的是,让第1列到第15列之间的item按照double的值⼤⼩来排序。5、修改item时,使⽤下⾯的⽅式,还得稍作改变(dynamic_cast),可能还有更优雅的⽅式。
QuoteItem *oldItem = dynamic_cast<QuoteItem*>(model->item(row, column));