[PyQt] QTableView 添加代理显示控件

4 篇文章 0 订阅

照着《C++ Gui Qt 编程》里照葫芦画飘成功了,我好棒棒

添加QComBox也成功

class SpinBoxDelegate(QItemDelegate):
    def __init__(self, column, parent=None):
        super(SpinBoxDelegate, self).__init__(parent)
        self.column = column

    def paint(self, painter, option, index):
        if index.column() == self.column:
            value = index.model().data(index, Qt.DisplayRole)
            option.displayAlignment = Qt.AlignRight | Qt.AlignVCenter
            self.drawDisplay(painter, option, option.rect, str(value) if value is not None else None)
            self.drawFocus(painter, option, option.rect)
        else:
            super(SpinBoxDelegate, self).paint(painter, option, index)

    def createEditor(self, parent, option, index):
        if index.column() == self.column:
            spinBox = QSpinBox(parent)
            spinBox.setRange(0, 2000)
            spinBox.editingFinished.connect(self.commitAndCloseEditor)
            return spinBox
        else:
            return super(SpinBoxDelegate, self).createEditor(parent, option, index)

    def commitAndCloseEditor(self):
        spinBox = self.sender()
        self.commitData.emit(spinBox)
        self.closeEditor.emit(spinBox)

    def setEditorData(self, editor, index):
        if index.column() == self.column:
            value = index.model().data(index, Qt.DisplayRole)
            editor.setValue(value if value is not None else 0)
        else:
            super(SpinBoxDelegate, self).setEditorData(editor, index)

使用:

class TableView(QTableView):
    def __init__(self, parent=None):
        super(TableView, self).__init__(parent):
        self.model = QStandardItemModel(self)
        self.setModel(self.model)
        spinBoxDelegate = SpinBoxDelegate(1)  # 对第2列有效
        self.setItemDelegate(spinBoxDelegate)

效果:

在这里插入图片描述

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值