1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
# -*- coding: utf-8 -*-
from PySide import QtCore, QtGui
class CheckBoxDelegate(QtGui.QItemDelegate):
def __init__(self, parent=None):
QtGui.QItemDelegate.__init__(self, parent)
self.chkboxSize = 19 #?!
def createEditor(self, parent, option, index):
chkbox = QtGui.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 = QtGui.QStyleOptionButton()
opt.state |= QtGui.QStyle.State_Enabled | (QtGui.QStyle.State_On if value else QtGui.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 = QtGui.QRect(left, top, self.chkboxSize, self.chkboxSize)
QtGui.QApplication.style().drawControl(QtGui.QStyle.CE_CheckBox, opt, painter)
def updateEditorGeometry(self, editor, option, index):
pass
###############################################################################
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
table = QtGui.QTableView()
model = QtGui.QStandardItemModel(3, 3, table)
model.setHorizontalHeaderLabels(['Name', 'Description', 'Animal?'])
model.setData(model.index(0, 0, QtCore.QModelIndex()), QtCore.QVariant('Squirrel'))
model.setData(model.index(0, 1, QtCore.QModelIndex()), QtCore.QVariant(u'test'))
model.setData(model.index(0, 2, QtCore.QModelIndex()), QtCore.QVariant(True))
model.setData(model.index(1, 0, QtCore.QModelIndex()), QtCore.QVariant('Soybean'))
model.setData(model.index(1, 1, QtCore.QModelIndex()), QtCore.QVariant(u'essai'))
model.setData(model.index(1, 2, QtCore.QModelIndex()), QtCore.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_()) |
Partager