How to use QStandardItem subclass to sort by Chinese order
-
Hello,
Another sort question. I have a treeview to sort by Chinese phonetic alphabet, and i use a subclass ofQStandardItem
and reimplement operator'<' like Assitant told me, the code like:class MyOwnTreeItem: public QStandardItem { public: bool operator<(const MyOwnTreeItem&other) const { const int role = model() ? model()->sortRole() : Qt::DisplayRole; const QVariant l = data(role), r = other.data(role); QLocale local(QLocale::Chinese); QCollator collator(local); return collator.compare(l.toString(), r.toString()); }; }
insert in model
void MyOwnTreeModel::insertItem { MyOwnTreeItem*pItem = new MyOwnTreeItem(); /* add item data */ this->appendRow(pItem); }
and I call it like:
void MyOwnTreeWidget::sortItem { QList<QStandardItem *> itemList = pTreeModel->findItems("*", Qt::MatchWildcard | Qt:: MatchRecursive); /* find the parent item need to sort */ MyOwnTreeItem*pTreeItem = static_cast<MyOwnTreeItem*>(pParentItem); pTreeItem->sortChildren(0, Qt::AscendingOrder); }
but not works, can anyone tell me what's wrong of my code?
-
@Aizzzz said in How to use QStandardItem subclass to sort by Chinese order:
but not works
In what way "not works"? Does not get called? Gets called but does not do any sorting at all? Does sorting but does not respect the order you expect for Chinese? I would put a debug breakpoint in your
bool operator<
and see if that returns what you expect on each call. -
@Aizzzz said in How to use QStandardItem subclass to sort by Chinese order:
bool operator<(const MyOwnTreeItem&other) const { ... QCollator collator(local); return collator.compare(l.toString(), r.toString()); }
The function needs to return true if the this item is less than
other
, and false otherwise. QCollator::compare() does not return a bool, but the result will be converted: 0 becomes false, anything else true. So if this item equals other then false else true. -
@JonB
It's do sorting but does not as expected order. The result order is default order (seems be Utf-8 encode order, Google tell me the GB encode will order as I expected), even if I tryreturn true
inbool operator<
, its still sort by the default order. Now it looks like operator < is not called, still useQStandardItem::operator<(const QStandardItem &other) const
.
And the Visual Studio 2017 tell me the breakpoint not avaliable :( -
@Aizzzz
bool QStandardItem::operator<(const QStandardItem &other) const is the signature and I see it is markedvirtual
. Make sure your signature matches exactly. Add the keywordoverride
at the end of your subclassed declaration. This will warn you if you have not got the correct exact declaration.