2015-03-03 50 views
3

我是字符串的下面收集使用QString::localeAwareCompare进行排序:使用自定义字符串排序

检索词: “山”

结果:

  • 精灵登山
  • Madblind Mountain
  • Magnetic Mountain
  • 山羊
  • 登山大本营
  • 山泰坦
  • 山谷
  • 山雪人
  • 覆雪山脉
  • 的山

的夫人订单按照的词汇排序。 最后我想以具有下列规则:

  1. 在顶部
  2. 精确匹配与前词法排序的值精确匹配。包含在字
  3. 匹配词法排序

    • 山(1)
    • 山羊(2)
    • 山要塞(2)
    • 山泰坦(2)
    • 山谷( 2)
    • Mountain Yeti(2)
    • 地精登山者(3)
    • Madblind山(3)
    • 磁山(3)
    • 覆雪山脉(3)
    • 山夫人(3)

有谁知道这可能实现?我能够实现某种类型的自定义排序。

编辑:

下面是一些janky代码中,我试图让精确匹配的顶端,其工作。

bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { 

    QString leftString = sourceModel()->data(left).toString(); 
    QString rightString = sourceModel()->data(right).toString(); 

    if (leftString.compare(cardName, Qt::CaseInsensitive) == 0) {// exact match should be at top 
     return true; 
    } 

    if (rightString.compare(cardName, Qt::CaseInsensitive) == 0) {// exact match should be at top 
     return false; 
    } 

    return QString::localeAwareCompare(leftString, rightString) < 0; 

} 
+0

显示你试过的东西 – 2015-03-03 11:37:23

+0

@ ArunA.S增加了一些我曾作为实验尝试过的东西。 – maffo 2015-03-03 11:40:00

回答

2

这是一种可以完成当前代码的方法。它试图从最特殊到最常见的情况进行排序:精确匹配,匹配加东西,其他所有事情。

bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, 
           const QModelIndex &right) const { 

    QString leftString = sourceModel()->data(left).toString(); 
    QString rightString = sourceModel()->data(right).toString(); 

    // The exact match (if any) should be at the top 
    if (leftString.compare(cardName, Qt::CaseInsensitive) == 0) 
     return true; 
    if (rightString.compare(cardName, Qt::CaseInsensitive) == 0) 
     return false; 

    // We know that neither is the perfect match. 
    // But is either a match-plus-some-stuff ? 
    bool isLeftType2 = leftString.startsWith(cardName, Qt::CaseInsensitive); 
    bool isRightType2 = rightString.startsWith(cardName, Qt::CaseInsensitive); 
    if (isLeftType2 && !isRightType2) 
     return true; 
    if (isRigthType2 && !isLeftType2) 
     return false; 

    // At this point we're sorting two matches of the same type 
    // Either both are matches-plus-some-stuff or partial matches 
    return QString::localeAwareCompare(leftString, rightString) < 0; 
} 

我认为像“登山”单独将2型而不是3型,你可以在比较中添加+" ",如果你不希望出现这种情况。