How to restrict the values in the QTableview only to positive using setData?
-
I have a QStandardItemModel set to tableView. I want to restrict the values to only positive
How to restrict the values in the QTableview only to positive using setData?QStandardItemModel *dataTableModel = new QStandardItemModel(8,4); ui->tableView_datatable->setModel(dataTableModel); int row = 8; int col = 4; for(int i = 0; i < col ; i++) { for(int j = 0; j< row ; j++) { QModelIndex index= dataTableModel->index(i,j,QModelIndex()); dataTableModel->setData(index,i); } }
-
you need to create a custom item delegate (derived from QStyledItemDelegate) and override it's createEditor() method.
Following should do what you want:
class MyItemDelegate : public QStyledItemDelegate { Q_OBJECT public: ... virtual QWidget * createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const { QWidget* editor = QStyledItemDelegate::createEditor(parent, option, index); if( QSpinBox* spinBox = qobject_cast<QSpinBox>(editor) ) spinBox->setMinimum(0); return editor; } };
And of course finally set it on your table view widget:
ui->tableView_datatable->setItemDelegate( new MyItemDelegate(ui->tableView_datatable) );
-
@raven-worx
Thanks for the reply.
I do not have spinbox set to my table. Using setdata each cell of the tableturns out to be spinbox (not sure if it is spin box). can we do it without custom item delegate?
It works with custom ItemDelegate. but i already have a delegate in my project with comboboxQWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & option , const QModelIndex & index ) const { QComboBox *editor = new QComboBox(parent); editor->addItems(comboItems); return editor; }
can we implement spinbox and combobox in single delegate and use it for two different table?
-
can we implement spinbox and combobox in single delegate?
sure you can: You also get the QModelIndex passed as parameter. Use this to either check the column or to retrieve any custom data (e.g. via data item role).
-
@raven-worx
checking column of one table will effect other table?