【问题标题】:Sorting QTableWidget Items Numerically以数字方式对 QTableWidget 项进行排序
【发布时间】:2014-08-27 17:10:28
【问题描述】:

启用排序时在 PyQt4 中使用 QTableWidget,项目被排序为字符串。

变量 = [1,2,3,4,5,11,22,33]

产生订单

1 11 2 22 3 33 4 5

我目前正在使用下面的代码来填表

tableWidgetData.setItem(0, 0, QtGui.QTableWidgetItem(variable))

我已经尝试过,因为我认为变量只作为字符串排序,因为它们是字符串

tableWidgetData.setItem(0, 0, QtGui.QTableWidgetItem(int(variable)))

但这是不可能的。我哪里错了?

【问题讨论】:

    标签: python sorting python-2.7 pyqt4 qtablewidget


    【解决方案1】:

    如果在QtGui.QTableWidgetItem 构造函数中传递变量,我必须是QtCore.QString ot python sring。

    要修复它,请创建您的自定义 QtGui.QTableWidgetItem 并通过 overidebool QTableWidgetItem.__lt__ (self, QTableWidgetItem other) 实现小于(或者我们知道在 python 中为 object.__lt__(self, other))的检查案例。

    示例;

    import sys
    import random
    from PyQt4 import QtCore, QtGui
    
    class QCustomTableWidgetItem (QtGui.QTableWidgetItem):
        def __init__ (self, value):
            super(QCustomTableWidgetItem, self).__init__(QtCore.QString('%s' % value))
    
        def __lt__ (self, other):
            if (isinstance(other, QCustomTableWidgetItem)):
                selfDataValue  = float(self.data(QtCore.Qt.EditRole).toString())
                otherDataValue = float(other.data(QtCore.Qt.EditRole).toString())
                return selfDataValue < otherDataValue
            else:
                return QtGui.QTableWidgetItem.__lt__(self, other)
    
    class QCustomTableWidget (QtGui.QTableWidget):
        def __init__ (self, parent = None):
            super(QCustomTableWidget, self).__init__(parent)
            self.setColumnCount(2)
            self.setRowCount(5)
            for row in range(self.rowCount()):
                self.setItem(row, 0, QCustomTableWidgetItem(random.random() * 1e4))
                self.setItem(row, 1, QtGui.QTableWidgetItem(QtCore.QString(65 + row)))
            self.setSortingEnabled(True)
    
    myQApplication = QtGui.QApplication([])
    myQCustomTableWidget = QCustomTableWidget()
    myQCustomTableWidget.show()
    sys.exit(myQApplication.exec_())
    

    【讨论】:

    • 谢谢,创建一个自定义的 QtGui.QTableWidgetItem 是这样做的方法。现在效果很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 2015-06-27
    • 1970-01-01
    相关资源
    最近更新 更多