使用QTableWidget中的setCellWidget对列进行排序

时间:2015-10-27 10:20:42

标签: python-2.7 sorting pyqt pyqt4 qtablewidget

我正在尝试对包含进度条的列进行排序。我希望列按进度条值排序。任何帮助都感激不尽 enter image description here

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys


class Example(QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.tablew = Table(self)
        self.setCentralWidget(self.tablew)

        self.setGeometry(300, 300, 300, 200)
        self.show()


class ProgressBar(QProgressBar):

    def __init__(self, value, parent=None):
        QProgressBar.__init__(self)
        self.setMinimum(1)
        self.setMaximum(5.0)
        self.setValue(value)
        self.setFormat('{0:.5f}'.format(value))
        style = ''' QProgressBar{max-height: 15px;text-align: center;}'''
        self.setStyleSheet(style)


class Table(QTableWidget):

    def __init__(self,   parent=None):
        QTableWidget.__init__(self)
        self.setColumnCount(2)
        self.setHorizontalHeaderLabels(['id', 'status'])
        header = self.horizontalHeader()
        header.setResizeMode(QHeaderView.Stretch)
        self.setSortingEnabled(True)
        self.loadData()
        #

    def loadData(self):
        #
        tableData = [[89, 4.8], [99, 3.9], [101, 2.6], [105, 4]]
        #
        self.setRowCount(len(tableData))
        #
        for index, value in enumerate(tableData):
            # column1
            item = QTableWidgetItem()
            item.setData(Qt.DisplayRole, value[0])
            self.setItem(index, 0, item)
            # column2
            self.setCellWidget(index, 1, ProgressBar(value[1]))
        #


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

更新 根据@ekhumoro的回答 下面是完整的代码,但不知何故,它排序正确。 手动排序列后附加的屏幕截图 probelm in sorting

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys


class Example(QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.tablew = Table(self)
        self.setCentralWidget(self.tablew)

        self.setGeometry(300, 300, 300, 200)
        self.show()


class ProgressBar(QProgressBar):

    def __init__(self, value, parent=None):
        QProgressBar.__init__(self)
        self.setMinimum(1)
        self.setMaximum(5.0)
        self.setValue(value)
        self.setFormat('{0:.5f}'.format(value))
        style = ''' QProgressBar{max-height: 15px;text-align: center;}'''
        self.setStyleSheet(style)


class Table(QTableWidget):

    def __init__(self,   parent=None):
        QTableWidget.__init__(self)
        self.setColumnCount(2)
        self.setHorizontalHeaderLabels(['id', 'status'])
        header = self.horizontalHeader()
        header.setResizeMode(QHeaderView.Stretch)
        self.setSortingEnabled(True)
        self.loadData()
        #

    def loadData(self):
        #
        tableData = [[89, 4.8], [99, 3.9], [101, 2.6], [105, 4]]
        #
        self.setRowCount(len(tableData))
        #
        for index, value in enumerate(tableData):
            # column1
            item = QTableWidgetItem()
            item.setData(Qt.DisplayRole, value[0])
            self.setItem(index, 0, item)
            # column2
            item = ProgressWidgetItem()
            self.setItem(index, 1, item)
            item.updateValue(value[1])
            progress = ProgressBar(value[1])
            self.setCellWidget(index, 1, progress)
            progress.valueChanged.connect(item.updateValue)
        self.sortItems(1, Qt.DescendingOrder)


class ProgressWidgetItem(QTableWidgetItem):

    def __lt__(self, other):
        return self.data(Qt.UserRole) < other.data(Qt.UserRole)

    def updateValue(self, value):
        self.setData(Qt.UserRole, value)


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:3)

您可以继承QTableWidgetItem并重新实现__lt__,然后将空白项添加到进度条列:

            # column2
            item = ProgressWidgetItem()
            self.setItem(index, 1, item)
            item.updateValue(value[1])
            progress = ProgressBar(value[1])
            self.setCellWidget(index, 1, progress)
            progress.valueChanged.connect(item.updateValue)
        self.sortItems(1, Qt.DescendingOrder)


class ProgressWidgetItem(QTableWidgetItem):
    def __lt__(self, other):
        # python 3
        # return self.data(Qt.UserRole) < other.data(Qt.UserRole)
        # python 2
        return (self.data(Qt.UserRole).toPyObject() <
                other.data(Qt.UserRole).toPyObject())

    def updateValue(self, value):
        self.setData(Qt.UserRole, value)

<强> PS

对于Python 2和Python 3,__lt__的实现是不同的,因为默认情况下,后者将返回普通的Python类型而不是QVariantQString。可以直接测试两个QVariant对象是否相等,而不是一个是否小于另一个(即使它们包含相同类型的值)。

在Python 2中,您可以通过在应用程序中的第一个PyQt导入之前放置以下代码来消除QVariantQString

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

这将使行为与Python 3相同,这意味着您永远不必使用丑陋的代码,如variant.toPyObject()str(qtstring)