PyQt QTableView嵌入QCheckBox

  原文链接:PyQt QTableView嵌入QCheckBox

  关联文章:PyQt QTableView嵌入QComboBox

  Qt里在QTableView中嵌入QCheckBox挺简单,用QItemDelegate就可以很方便地实现,不过要想让CheckBox居中则有点麻烦,好在稍稍做一些处理就可以实现,下面以PyQt为例(提示:一个CheckBoxDelegate可以用于多个列):

#coding=utf-8

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

class CheckBoxDelegate(QItemDelegate):

  def __init__(self, parent=None):
    QItemDelegate.__init__(self, parent)
    self.chkboxSize = 19 #?!

  def createEditor(self, parent, option, index):
    chkbox = QCheckBox(parent)
    chkbox.setText('')
    chkbox.setTristate(False) #只用两个状态
    left = option.rect.x() + (option.rect.width() - self.chkboxSize) / 2
    top  = option.rect.y() + (option.rect.height() - self.chkboxSize) / 2
    chkbox.setGeometry(left, top, self.chkboxSize, self.chkboxSize)
    return chkbox

  def paint(self, painter, option, index):
    value = index.data().toBool()
    opt = QStyleOptionButton()
    opt.state |= QStyle.State_Enabled | (QStyle.State_On if value else QStyle.State_Off)
    opt.text = ''
    left = option.rect.x() + (option.rect.width() - self.chkboxSize) / 2
    top  = option.rect.y() + (option.rect.height() - self.chkboxSize) / 2
    opt.rect = QRect(left, top, self.chkboxSize, self.chkboxSize)
    QApplication.style().drawControl(QStyle.CE_CheckBox, opt, painter)

  def updateEditorGeometry(self, editor, option, index):
    pass

###############################################################################

if __name__ == '__main__':

  import sys

  app = QApplication(sys.argv)

  table = QTableView()
  model = QStandardItemModel(3, 3, table)
  model.setHorizontalHeaderLabels(['Name', 'Description', 'Animal?'])
  model.setData(model.index(0, 0, QModelIndex()), QVariant('Squirrel'))
  model.setData(model.index(0, 1, QModelIndex()), QVariant(u'可爱的松树精灵'))
  model.setData(model.index(0, 2, QModelIndex()), QVariant(True))
  model.setData(model.index(1, 0, QModelIndex()), QVariant('Soybean'))
  model.setData(model.index(1, 1, QModelIndex()), QVariant(u'他站在田野里吹风'))
  model.setData(model.index(1, 2, QModelIndex()), QVariant(False))
  table.setModel(model)
  table.setItemDelegateForColumn(2, CheckBoxDelegate(table))
  table.resizeColumnToContents(1)
  table.horizontalHeader().setStretchLastSection(True)
  table.setGeometry(80, 20, 400, 300)
  table.setWindowTitle('Grid + CheckBox Testing')
  table.show()

  sys.exit(app.exec_())
  下面是在Ubuntu中的效果图:

Ubuntu下的效果图

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值