Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTableWidget: Only numbers permitted

Is there any way to disallow any characters except numbers (0-9) in a QTableWidget? For QLineEdits I'm using a RegEx validator, but this is not available for QTableWidgets. I thought of inserting QLineEdits in as CellWidgets into the table, but then I had to rewrite an extreme large amount of functions in my code. So, is there any other (direct) way to do so?

like image 217
KrauseDroid Avatar asked Dec 09 '25 09:12

KrauseDroid


1 Answers

I would suggest using an item delegate for your table widget to handle the possible user input. Below is a simplified solution.

The implementation of item delegate:

class Delegate : public QItemDelegate
{
public:
    QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem & option,
                      const QModelIndex & index) const
    {
        QLineEdit *lineEdit = new QLineEdit(parent);
        // Set validator
        QIntValidator *validator = new QIntValidator(0, 9, lineEdit);
        lineEdit->setValidator(validator);
        return lineEdit;
    }
};

Implementation of the simple table widget with the custom item delegate:

QTableWidget tw;
tw.setItemDelegate(new Delegate);
// Add table cells...
tw.show();
like image 75
vahancho Avatar answered Dec 11 '25 22:12

vahancho