我可以覆盖对QListWidgetItem的比较器的输入吗?(PyQt)

2024-10-02 08:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将QListWidget中的小部件设置为我自己的ProductItemWidget类,以便能够对列表中的项进行更多的定制。这很好,但我无法让列表自动排序。我打电话来

my_list.setSortingEnabled(True)

然后我尝试覆盖ProductListItem的“<;”比较器,我创建它是为了能够覆盖这个函数。在widget中,比较了getti()和它们调用的两个函数。这里的问题是,默认情况下,函数将第二个参数强制转换为QListWidgetItem,因此在我的代码中,我为self获取ProductListItem,而为otherItem获取QListWidgetItem。otherItem不允许我访问它对应的ProductItemWidget,因为访问它的唯一方法是将ProductListItem传递给QListWidget的itemWidget()调用。这是我的代码:

^{pr2}$

有什么方法可以防止调用\ult\uuuu将otherItem强制转换为QListWidgetItem吗?在

我已经在这个问题上纠结了一段时间,所以任何建议都将不胜感激。我愿意改变我的整个方法。在


Tags: 方法函数代码true列表排序部件my
1条回答
网友
1楼 · 发布于 2024-10-02 08:19:51

QListWidget是“便利”类之一(如QTreeWidget和QTableWidget)。只要您的需求非常简单,使用它们就可以了。但一旦你想要一个更复杂的东西,这种僵化很快就会显现出来。在

通过切换到具有QStandardItemModel的更通用的QListView类,您可以相当容易地解决问题。这需要更多的工作来设置,但它将立即带来更多的灵活性。在

下面是基于示例代码的该方法的演示:

from PyQt4 import QtGui

class ProductListItem(QtGui.QStandardItem):
    def __lt__(self, other):
        listview = self.model().parent()
        this_widget = listview.indexWidget(self.index())
        other_widget = listview.indexWidget(other.index())
        return this_widget.getText() < other_widget.getText()

class ProductItemWidget(QtGui.QWidget):
    def __init__(self, product_name, parent=None):
        super(ProductItemWidget, self).__init__(parent)
        self.label = QtGui.QLabel(product_name, self)
        layout = QtGui.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.label)

    def getText(self):
        return self.label.text()

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.list = QtGui.QListView(self)
        layout = QtGui.QHBoxLayout(self)
        layout.addWidget(self.list)
        # model must have the listview as parent
        model = QtGui.QStandardItemModel(self.list)
        self.list.setModel(model)
        for key in 'MHFCLNIBJDAEGK':
            item = ProductListItem()
            model.appendRow(item)
            widget = ProductItemWidget('Item %s' % key, self.list)
            self.list.setIndexWidget(item.index(), widget)
        model.sort(0)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 150, 300)
    window.show()
    sys.exit(app.exec_())

相关问题 更多 >

    热门问题