Qt World Summit: Register Today!

QTableWidget: Only numbers (delegate)

  • 'm currently trying to let my QTableWidget only display numbers. I read that I'd need a QAbstractItemDelegate to do so, so I read through the documentation and found the createEditor void. Here's my code I'm currently using:

    @#include "tabledelegate.h"

    TableDelegate::TableDelegate(QObject *parent) : QStyledItemDelegate(parent)

    QWidget* TableDelegate::createEditor(QWidget* parent,const QStyleOptionViewItem &option,const QModelIndex &index) const
    QLineEdit* editor = new QLineEdit(parent);
    QDoubleValidator* val = new QDoubleValidator(editor);
    return editor;

    And I'm trying to call the Delegate by doing this in the constructor of MainWindow:

    @ui->tableWidget->setItemDelegate(new TableDelegate(ui->tableWidget));@

    But it gives me this error:

    bq. no matching function for call to 'QTableWidget::setItemDelegate(TableDelegate*)' ui->tableWidget->setItemDelegate(new TableDelegate(ui->tableWidget)); ^


  • Okay, I just forgot to subclass QStyledItemDelegate in my headerfile. But now I receive a new error at:
    @TableDelegate::TableDelegate(QObject *parent) : QStyledItemDelegate(parent)@

    bq. undefined reference to `vtable for TableDelegate'

  • Lifetime Qt Champion


    You need to rerun qmake before building or do a clean rebuild

  • Yep, I also forgot to reimplement the three other functions which are needed:

    "In this case, the following virtual functions must be reimplemented:
    createEditor() returns the widget used to change data from the model and can be reimplemented to customize editing behavior.
    setEditorData() provides the widget with data to manipulate.
    updateEditorGeometry() ensures that the editor is displayed correctly with respect to the item view.
    setModelData() returns updated data to the model."

    After doing so and running a qmake, it works. Well, at least it compiles. Whenever I click on a cell in my QTableWidget now:
    The validator works, but when I click enter/go onto another cell, the cell isn't filled. Also, this looks pretty dumb.

    /edit: Nevermind. The three other functions which need to be reimplemented have got a reason, I see. Got a quick look through the docs again and managed to do it. It works as it should now! Thanks anyways, SGaist.

  • When you select an other cell, the model you have will be called in the setData() function. There you will need to store the data into your model container to keep the new value. Otherwise the old value will be kept. This is handy for validation purposes.
    For the display of your delegate look into your updateEditorGeometry settings!

  • I've edited my above post already, managed to do it myself. Thanks though!

Log in to reply