Home > Net >  How to set QTable cell always in edit mode?
How to set QTable cell always in edit mode?

Time:03-25

I have a table that need all table cell always in edit mode, I forgot how to set this behavior now, can someone give some tips?

The Demo

import os
import platform 
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class SpinBoxDelegate(QStyledItemDelegate):

    def createEditor(self, parent: QWidget, option: 'QStyleOptionViewItem', index: QModelIndex) -> QWidget:
        editor = QSpinBox(parent)
        
        editor.setRange(0, 10)
        return editor
    
    def setEditorData(self, editor: QWidget, index: QModelIndex) -> None:
        value = index.data(Qt.EditRole)
        if value is None: value = 0
        
        editor.setValue(value)
    
    def setModelData(self, editor: QWidget, model: QAbstractItemModel, index: QModelIndex) -> None:
        value = editor.value()
        model.setData(index, value, Qt.EditRole)
    
    def updateEditorGeometry(self, editor: QWidget, option: 'QStyleOptionViewItem', index: QModelIndex) -> None:
       editor.setGeometry(option.rect)
       
       
app  = QApplication([])
win = QTableWidget()
win.setColumnCount(20)
win.setRowCount(20)

win.setItemDelegate(SpinBoxDelegate())
for row in range(win.rowCount()):
    for col in range(win.columnCount()):
        win.openPersistentEditor(win.item(row,col))

win.resize(1000, 500)
win.show()
app.exec()

I hear there have two methods, 1st is use openPersistentEditor and 2rd is use QStyledItemDelegate, but I forgot to how to do it now and my code sample not working.

CodePudding user response:

In a QTableWidget, although there are rows and columns, it does not imply that there are QTableWidgetItems associated with the cells. In this case, the item method is returning None, so openPersistentEditor will do nothing. The solution is to set QTableWidgetItem on each cell.

for row in range(win.rowCount()):
    for col in range(win.columnCount()):
        it = win.item(row, col)
        if it is None:
            it = QTableWidgetItem()
            win.setItem(row, col, it)
        win.openPersistentEditor(it)
  • Related