How to set limits on the text entered in any cell of a QTableView?



  • Hello,

    I'm trying to do a crossword game using QT. I'm using QTableView for this and It should be that the user can enter one and only one letter in any of the editable cells in the QTableView. The problem is that I cannot seem to figure out how to put limits or restrictions on what the user can enter in each editable cell. How to do it? I have looked at QT documentation, searched online, looked in key/mouse events in QT but still I did not get how to do it. Any help well be appreciated. Thank you.



  • Hi Mezzo,

    the trick you need is named: QStyledItemDelegate :-)

    The delegate handles the input editors (and also painting) for cells of a view.
    You create the editors there, so you can create a line edit with input restrictions :-)



  • I would indeed subclass QStyledItemDelegate, and reimplement the createEditor method to something like this:

    @
    QWidget* OneLetterDelegate::createEditor ( QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index ) const
    {
    //let QStyledItemDelegate do the hard work and create an editor
    QWidget* widget = QStyledItemDelegate::createEditor(parent, option, index);

    //If the editor is a a QLineEdit, we apply our limits:
    QLineEdit* lineEdit = qobject_cast<QLineEdit*>(widget);
    if (lineEdit) {
         lineEdit->setInputmask("a");
    }
    
    return widget;
    

    }
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.