13,009
回編集
60行目: | 60行目: | ||
リストの標準メソッドに存在するソートを使用すると、"file1 file10 file11 file2 ..."のように並び替えられてしまう。<br> | リストの標準メソッドに存在するソートを使用すると、"file1 file10 file11 file2 ..."のように並び替えられてしまう。<br> | ||
<br> | <br> | ||
数値の大きさ順にファイルを並べるソートをナチュラルソートと呼ぶが、現在、QtのAPIには該当機能は実装されていないため、<br> | |||
Windowsの場合、<code>StrCmpLogicalW</code> | ナチュラルソート関数を作成する必要がある。<br> | ||
<br> | |||
Windowsの場合、<code>StrCmpLogicalW</code>関数を使用して、ナチュラルソートを実装することができる。 <br> | |||
<syntaxhighlight lang="c++"> | <syntaxhighlight lang="c++"> | ||
// MainWindow.cpp | // MainWindow.cpp | ||
#if defined(Q_OS_WIN) | |||
// 比較関数 | // 比較関数 | ||
bool MainWindow::lessThan(QString &left, QString &right) | bool MainWindow::lessThan(QString &left, QString &right) | ||
{ | { | ||
LPCWSTR pszwLeft, pszwRight; | LPCWSTR pszwLeft, pszwRight; | ||
pszwLeft = (LPCWSTR)left.unicode(); | pszwLeft = (LPCWSTR)left.unicode(); | ||
pszwRight = (LPCWSTR)right.unicode(); | pszwRight = (LPCWSTR)right.unicode(); | ||
return StrCmpLogicalW(pszwLeft, pszwRight) < 0; | return StrCmpLogicalW(pszwLeft, pszwRight) < 0; | ||
} | } | ||
#endif | |||
// 複数選択したファイルリストをリストウィジェットに追加する関数 | // 複数選択したファイルリストをリストウィジェットに追加する関数 | ||
void MainWindow::browseImage() | void MainWindow::browseImage() | ||
{ | { | ||
QStringList | QStringList listFileName = QFileDialog::getOpenFileNames(this, "Select files", "<検索ディレクトリのパス>", "File(*.*)"); | ||
if( | if(listFileName.size() == 0) | ||
{ | { // ファイルが存在しない場合 | ||
return; | return; | ||
} | } | ||
qSort( | #if defined(Q_OS_WIN) | ||
qSort(listFileName.begin(), listFileName.end(), lessThan); | |||
#elif defined(Q_OS_LINUX) | |||
QCollator collator; | |||
collator.setNumericMode(true); | |||
std::sort(listFileName.begin(), listFileName.end(), [&collator](const QString &file1, const QString &file2) | |||
{ | |||
return collator.compare(file1, file2) < 0; | |||
}); | |||
#endif | |||
for(int i = 0; i < | for(int i = 0; i < listFileName.size(); i++) | ||
{ | { | ||
listWidget->addItem( | listWidget->addItem(listFileName.at(i)); | ||
} | } | ||
} | } | ||
107行目: | 117行目: | ||
void browseImage(); | void browseImage(); | ||
#if defined(Q_OS_WIN) | |||
static bool lessThan(QString &left, QString &right); | static bool lessThan(QString &left, QString &right); | ||
#endif | |||
// ...略 | // ...略 | ||
113行目: | 126行目: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<br> | <br> | ||
<code>QTreeView</code>クラスや<code>QTableView</code>クラスの場合は、<code>QSortFilterProxyModel</code>クラスを継承した派生クラスを作成して、ナチュラルソート関数を作成する方法もある。<br> | |||
以下のGoogle codeのプロジェクトが採用している。<br> | 以下のGoogle codeのプロジェクトが採用している。<br> | ||
[http://code.google.com/p/kamicmd/ kamicmd - Modern file manager - Google Project Hosting]<br> | [http://code.google.com/p/kamicmd/ kamicmd - Modern file manager - Google Project Hosting]<br> |