此代码创建一个QTableView
,其中QSpinBoxes
设置为其委派的项目。我想使用SpinBoxDelegate
的{{1}}方法根据此处描述的技术返回固定的sizeHint()
:
Adjusting the height of a QTableView Row
不幸的是,只为单行#1(?)返回指定的QSize(64,64)
。为什么每一行都不会发生?代码中的错误在哪里?
QSize(64,64)
答案 0 :(得分:1)
错误是使用tableView.resizeRowToContents(True)
而不是tableView.resizeRowsToContents()
来更新所有当前可见的QModelIndexes。固定代码如下:
import sip
sip.setapi('QVariant', 2)
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class SpinBoxDelegate(QItemDelegate):
def createEditor(self, parent, option, index):
editor = QSpinBox(parent)
editor.setMinimum(0)
editor.setMaximum(100)
return editor
def setEditorData(self, spinBox, index):
value = index.model().data(index, Qt.EditRole)
spinBox.setValue(value)
def setModelData(self, spinBox, model, index):
spinBox.interpretText()
value = spinBox.value()
model.setData(index, value, Qt.EditRole)
def updateEditorGeometry(self, editor, option, index):
print option
editor.setGeometry(option.rect)
def sizeHint(self, option, index):
print 'sizeHint', index.row(), index.column()
return QSize(64,64)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
model = QStandardItemModel(4, 2)
tableView = QTableView()
tableView.setModel(model)
delegate = SpinBoxDelegate()
tableView.setItemDelegate(delegate)
for row in range(4):
for column in range(2):
index = model.index(row, column, QModelIndex())
model.setData(index, (row + 1) * (column + 1))
tableView.resizeRowsToContents()
tableView.show()
sys.exit(app.exec_())
或者这是相同概念的骨架版本:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class ForSizeOnlyDelegate(QItemDelegate):
def sizeHint(self, option, index):
print 'sizeHint', index.row(), index.column()
return QSize(64,64)
if __name__ == '__main__':
app = QApplication(sys.argv)
model = QStandardItemModel(14, 12)
tableView = QTableView()
tableView.setModel(model)
delegate = ForSizeOnlyDelegate()
tableView.setItemDelegate(delegate)
tableView.resizeRowsToContents()
tableView.show()
sys.exit(app.exec_())