QSqlTableModel - Check for invalid cells in QTableView?
Unsolved
General and Desktop
-
Hi, I have a
QSqlTableModel
set on aQTableView
. When adding or updating a row I do not want to allow empty text in a specific column.On submit, I would like a messagebox to show and the focus set back on the invalid cell.
I haven't been able to find a simplified way to do this. I am aware of the
beforeInsert()
andbeforeUpdate()
signals where I could check if the data is valid, however I don't know how to stop the insertion/update if record is invalid. -
@R-P-H
I think there are various possibilities depending on exactly what you want. Here are some suggestions:- For the specific case of "don't allow empty" you could place a validator on the generated edit widget.
- To refuse a value for a certain index you could override
setData()
and return false. - To validate all data you could override
submit()
/submitAll()
and have them return false. However with these I don't think you know which things have changed. - Editing from a
QTableView
is done via an item delegate. Normally it generates a suitable delegate widget. You can provide your own subclassed delegate (QStyledItemDelegate
). From https://doc.qt.io/qt-6/qabstractitemdelegate.html you can implement your ownsetModelData()
which refuses to submit the data to the model if it considers it invalid. This might be a suitable place to show the user a message box.