PyQt QTableView嵌入QCheckBox

来源:互联网 发布:d3.js 弧线 编辑:程序博客网 时间:2024/06/07 05:37

  原文链接:PyQt QTableView嵌入QCheckBox

  关联文章:PyQt QTableView嵌入QComboBox

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

#coding=utf-8from 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下的效果图

原创粉丝点击