2015-03-03 45 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型,你可以在比較中添加+" ",如果你不希望出現這種情況。