您可以派生自己的QTableWidgetItem 类,然后编写自己的__lt__ 运算符。这也将减少对额外列的需求。大致如下:
from PyQt4 import QtCore, QtGui
import sys
import datetime
class MyTableWidgetItem(QtGui.QTableWidgetItem):
def __init__(self, text, sortKey):
#call custom constructor with UserType item type
QtGui.QTableWidgetItem.__init__(self, text, QtGui.QTableWidgetItem.UserType)
self.sortKey = sortKey
#Qt uses a simple < check for sorting items, override this to use the sortKey
def __lt__(self, other):
return self.sortKey < other.sortKey
app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()
window.setGeometry(0, 0, 400, 400)
table = QtGui.QTableWidget(window)
table.setGeometry(0, 0, 400, 400)
table.setRowCount(3)
table.setColumnCount(1)
date1 = datetime.date.today()
date2 = datetime.date.today() + datetime.timedelta(days=1)
date3 = datetime.date.today() + datetime.timedelta(days=2)
item1 = MyTableWidgetItem(str(date1.strftime("%A %d. %B %Y")), str(date1))
item2 = MyTableWidgetItem(str(date2.strftime("%A %d. %B %Y")), str(date2))
item3 = MyTableWidgetItem(str(date3.strftime("%A %d. %B %Y")), str(date3))
table.setItem(0, 0, item1)
table.setItem(2, 0, item2)
table.setItem(1, 0, item3)
table.setSortingEnabled(True)
window.show()
sys.exit(app.exec_())
这对我来说产生了正确的结果,您可以自己运行它来验证。单元格文本显示类似“Saturday 20. February 2010”之类的文本,但是当您按列排序时,它将正确按“2010-02-20”(iso 格式)的 sortKey 字段排序。
哦,还应注意,这不适用于 PySide,因为似乎 __lt__ 运算符未绑定,而 PyQt4 也是如此。我花了一段时间尝试调试它为什么不工作,然后我从 PySide 切换到 PyQt4,它工作正常。您可能会注意到__lt__ 未在此处列出:
http://www.pyside.org/docs/pyside/PySide/QtGui/QTableWidgetItem.html
但它就在这里:
http://doc.qt.digia.com/4.5/qtablewidgetitem.html#operator-lt