如何在QTableWidget中对数据进行排序? [英] How to sort data in QTableWidget?
问题描述
我有一个 QTableWidget
,第一列包含从 1 到 1000 的数字.现在我需要根据第一列对表格进行排序.
I have a QTableWidget
and the first column contains numbers from 1 to 1000. Now I need to sort the table based on this first column.
我正在使用函数 sortItems(int column, Qt::AscendingOrder)
,但它显示为:
I'm using the function sortItems(int column, Qt::AscendingOrder)
, but it is displayed as:
1, 10, 100, 1000, 101, 102, ...
1, 10, 100, 1000, 101, 102, ...
但我需要这个结果:
1, 2, 3 ,4...., 1000.
1, 2, 3 ,4...., 1000.
我正在使用 CSV 文件来填充表格.
I'm using a CSV file for populating the table.
推荐答案
最简单的方法可能是将 QTableWidgetItem 子类化,然后实现 <操作员对您正在排序数字而不是字符串这一事实要聪明.
The easiest way is probably to subclass QTableWidgetItem and then implement the < operator to be smart about the fact that you're sorting numbers and not strings.
class MyTableWidgetItem : public QTableWidgetItem {
public:
bool operator <(const QTableWidgetItem &other) const
{
return text().toInt() < other.text().toInt();
}
};
然后,当您填充表格时,您可以将自定义项的实例传递给它,这些实例知道如何正确排序而不是通用项.
Then when you're populating your table you can pass it instances of your custom items that know how to sort themselves properly instead of the generic ones.
这篇关于如何在QTableWidget中对数据进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!