Custom QStyledItemDelegate to customize apperence of QListView with a SQLModel under the hood
-
It's a two step operation:
- createEditor
- setEditorData
With the second you can set whatever is appropriate in the editor from your model.
-
@SGaist you are completly right, and I was confused following along the StarDelegate example that is diffrent from what I need.
So I adjust the EditorWidget with is own UI and the QPlainTextEdit, I was trying to test it but i notice that the "QStyledItemDelegate::createEditor()" is never called. I check online and the suggestion is to check the item's flags, so I did and the result is: "QFlagsQt::ItemFlag(ItemIsSelectable|ItemIsEnabled|ItemNeverHasChildren)".
As expected, the Items are missing the "isEditable" flags but I think there is not a direct way to modify ALL the item's flags at once from the QListView (at least from what I red).
Is my only choise left, to subclass QListView and re-implement the ::flags() method ?
this is my current basic setup in the main window for the default QListView:
// lst_vw rappresent the QListView placed in the UI file ui->lst_vw->setItemDelegate( new CommentListItem ); ui->lst_vw->setEditTriggers(QAbstractItemView::EditTrigger::DoubleClicked); ui->lst_vw->setModel(_m_model);
I already learn that this code inside MainWindow's constructor isn't enough.. what I'm asking is: Is it possible to set the editable flags without sub-classing the QListView and re-implement flags() ?
-
Usually this is done at the model level. Are you using one of the QSql models ?
-
@Andrea_Venturelli
Qt::ItemFlags
, includingQt::ItemIsEditable
and theflags()
method, come from the model, not from the view. So I don't know why you are thinking of subclassingQListView
, it does not store item flags or have aflags()
method to override.So you need to change what the model returns. Derive from
QAbstractItemModel
(or one of its existing derivations) and OR-in theItemIsEditable
to make the model editable. https://doc.qt.io/qt-6/qabstractitemmodel.html#subclassingTo enable editing in your model, you must also implement setData(), and reimplement flags() to ensure that ItemIsEditable is returned.
If you were using a
QListWidget
which hasQListWidgetItem
s you could callQListWidgetItem::setFlags()
to change an item's flags. However that is a "layer" added byQListWidget
to theQListView
you have. Internally it is presumably implemented byQListWidget
storing values to return from its model'sflags()
.For SQL stuff you should find that
QSqlQueryModel
returns non-editable flags (cannot edit items returned from a query), unless you subclass it. WhileQSqlTableModel
returns editable flags (can edit items stored in a table). You may want to subclass those, it might also be possible to interpose a (sub-classed)QAbstractProxyModel
where you overrideflags()
between your view and the SQL model.All ways round the one thing you do not need to do is change the
QListView
:) -
ahaha @JonB you are a legend, and I have a lot to study in order to understand very well the Model\View stuffs.
But bised that, you were right about the QSqlTableModel, and changing the model from QSqlQueryModel to it, "kinda worked"
Now (without trying to subclass anything) I got only the first item editable, and the others do not flinch.screenshot showing the first item is editable:
based on yours experience, which approach do you think is better and more elegant to resolve the problem (the problem is obviously my ignorance :) )?
-
The Query Model Example shows how to make a QSqlQueryModel editable.
-
@Andrea_Venturelli said in Custom QStyledItemDelegate to customize apperence of QListView with a SQLModel under the hood:
it, "kinda worked"
Now (without trying to subclass anything) I got only the first item editable, and the others do not flinch.I'm not sure what you're saying. From a
QSqlTableModel
you should be able to edit any/all columns, e.g. in aQTableView
, provided there is nothing "special" about their definitions. YourQListView
is only going to show/edit one column. Are you saying you have what you want or something else is a problem?If what you want to do is edit rows/columns in a SQL table
QSqlTableModel
should do fine. I think you only would want an editableQSqlQueryModel
instead in certain specialised circumstances.Don't forget there are two possibilities for presenting a UI to edit columns in tables. In one case the user does the edits "in situ" on items in the
QTableView
, by clicking on them there. This may indeed be what you want. But sometimes you might want to offer a "master-detail" view, where the user clicks on a row in the table view to read whichever editable fields into their own dedicated widgets not sitting on the table view. If you want that Qt offers QDataWidgetMapper. Just so you are aware. -
@JonB
I have a Sql model with all the informations needed to display the custom item inside a list view.the normal QStyledItemDelegate draw a rectangle with 3 labels (taken from the SqlModel):
-
- the string rappresenting the date when the message was first posted
-
- [optional] a string rappresenting the date when the “body” last modification occured (also taken from the Sql model, a empty string is provided if the comment was never edited before)
-
- the body containing a description about the problem or whatever (also present in the QSqlModel inside its specific column)
When the user double-click the comment he wants to modify, the createEditor() will provide the same data as before (post_date, post_modification_date if available, and the body text) but this time the body_text is not a label or a drawn text but it is a QPlainTextEdit.
I install a filterEvent on the QPlainTextEdit so when the user presses “Ctrl+Return” it emit a CommitAndCloseEditor signal to tell Qt to destroy the editor and save the data to the model (olso adding or updating the post_modified_date).
every rectangle rappresented inside the listView corresponds to a row of the model.
In the screenshot I posted, the first item , when double-clicked, work as expected and the Editor with the QPlainTextEdit. But if I try to do the same with the second, third and so on, the Editor don’t show up.
that’s all for the moment
-
-
@Andrea_Venturelli
I guess start by verifying whether the table view is seeing theItemIsEditable
flag for items when you double click (or whatever you have set) to edit them. Since that's talking about editing in place in aQTableView
I don't really see how that has anything to do with whatever you are doing with theQListView
. Or maybe you don't want cells editable in theQTableView
. Or maybe you want clicking in a cell in any column to invoke editing in theQListView
. I really don't know.In the screenshot I posted, the first item , when double-clicked, work as expected and the Editor with the QPlainTextEdit. But if I try to do the same with the second, third and so on, the Editor don’t show up.
First, second and third what?? What's an "item"? Are you talking about coulmns or rows or what? It would be a lot clearer if you stated this sort of thing.
UPDATE
Oh, I think your "items" are lines inside the List Item delegate, each of which corresponds to a column in the table view? So to edit columns within one row in the database. And you are having problems with which item you click and getting into the right edit. Or something like that. Quite outside of anything I have done. I just know about columns/row/cell editing, with or without delegates, of a table model in aQTableView
. -
Sorry @JonB I do not repeat an important point that I specified at the very early posts.
the table you see on the right is ONLY FOR DEBUG, on the final widget will only exist the “listView” with the custom delegate.
the table is only needed for me to troubleshoot potential errors and for the other here helping me understand what was given to the ListView!all the window is a test for develop the listView. it will be a stand alone widget where under it I’ll add a lineEdit to add new comments to the ListView.
THE TABLE IS ONLY FOR REFERENCE!Sorry if was not clear from the beginning
-
@Andrea_Venturelli
Yeah, that was my misunderstanding.You have a delegate which shows all the "columns" in one layout at different places. So won't you have to detect where user clicked to decide which "column" to edit?
-
not column , I go by row
every row is a record to my custom item in the ListViewid | body_text | post_date | modified_post_dt
1 basic text 12/02/2024 12/03/2024displayed as:
—————————-12/02/2024
12/03/2024
basic text
——————————
-
@Andrea_Venturelli
Yes I get that now. One list element shows all the columns in a database row, And you don't care where inside that user clicks because you only allow editing the comment column.So what you are saying is that the first row of the model is editable via the first item in the list view but the second is not, right? :) Then start by printing out the
flags()
for model index (row) 0 and 1 to verify the latter hasItemIsEditable
? -
exactly ! you get it right ahah
I printed the flags and the first give me “isEditable” with all the rest usual thinks (selectable, enabled, nochild)
but all the others don’t have it.. this looks strange to me. I’ll investigate deeper soon and I’ll post if I find something interesting -
@Andrea_Venturelli
That comes from the model'sflags()
implementation. Either you have done something there for row #0 but not others, or if you are saying this is directly theQSqlTableModel
then I don't see why it would return different values per row. -
@JonB , @SGaist after a little more debug this is what I noticed:
-
- the first item I DOUBLE-CLICK (editor trigger for modification) no matter if it was the first ListStyledItemDelegate rappresented in the ListView, the second, the third or the n_th element, became editable and remain editable. After that, all the others items flags are as default ( Selectable and Editable)
as you can see, the fourth item in the list is editable, because it was the first I double clicked.
If I close the application and run it again and double-clicking any other item first, it will be editable and the fourth is only selectable..
-
- after the body_text being changed, and the key Ctrl+Return being pressed (used for trigger CommitAndClose editor) the method "QStyledItemDelegate::setModelData( param1, param2, param3) doesn't set the new body text correctly as shown here:
void CommentListItem::setModelData( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const { if ( index.siblingAtColumn(2).data().canConvert<QString>() ) { qDebug() << "\n\t[::setModelData()] being called.."; \\ print_1 CommentEditor* cm_editor = qobject_cast<CommentEditor*>(editor); auto cmm_wdg = cm_editor->commentWidget(); auto body_txt = cmm_wdg.bodyText(); if ( cm_editor->bodyText() != body_txt ) { qDebug() << "\t[::setModelData()--> body_text different detected] inside if call.."; \\ print_2 /* generate the edited_mess_date */ QDateTime time_now = QDateTime::currentDateTime(); auto edited_mess_date = QString("Last Modification: "); edited_mess_date += time_now.toString("ddd, MMM dd HH:mm"); qDebug() << "\t - 'edited_mess_date' = " << edited_mess_date; \\ print_3 /* update the model */ qDebug() << "index.siblingAtColumn(4):\t" << index.siblingAtColumn(4); \\ print_4 qDebug() << "index.siblingAtColumn(5):\t" << index.siblingAtColumn(5); \\ print_5 model->setData( index.siblingAtColumn(4), QVariant::fromValue( body_txt ) ); model->setData( index.siblingAtColumn(5), QVariant::fromValue( edited_mess_date ) ); } } }
the prints are:
Ctrl + Return keys detected
committing editor...
[::setModelData()] being called.. <------- print_1[::setModelData()--> body_text different detected] inside if call.. <------- print_2 - 'edited_mess_date' = "Last Modification: Tue, Nov 05 09:30" <------- print_3
index.siblingAtColumn(4): QModelIndex(2,4,0x0,QSqlTableModel(0x23a1bceac10)) <------- print_4
index.siblingAtColumn(5): QModelIndex(2,5,0x0,QSqlTableModel(0x23a1bceac10)) <------- print_5 -
-
MainWindow code where the SetUp of the model occur.
private:
Ui::MainWindow ui;
QSqlDatabase _m_db;
QSqlQuery _m_query;
QSqlTableModel _m_model;MainWidow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); this->setUpDb(); // set the model to QList and QTable // _m_model = new QSqlQueryModel; _m_model = new QSqlTableModel; _m_model->setQuery("SELECT * FROM veh_comments;"); ui->tb_view->setModel(_m_model); auto header = ui->tb_view->horizontalHeader(); header->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tb_view->show(); ui->lst_vw->setItemDelegate( new CommentListItem ); ui->lst_vw->setEditTriggers(QAbstractItemView::EditTrigger::DoubleClicked); ui->lst_vw->setModel(_m_model); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_serach_le_returnPressed() { // read the id from the lineEdit auto id = ui->serach_le->text(); if (id == "") { QSqlQuery query("SELECT * FROM veh_comments"); _m_model->setQuery(std::move(query)); } else { // UPDATE VIEW auto query = commentsPerChassisId(id); _m_model->setQuery(std::move(query)); } qDebug() << "Line Edit \"Return_Key\" pressed..\n\n"; } QSqlQuery MainWindow::commentsPerChassisId(const QString& id) { QSqlQuery my_query(_m_db); my_query.prepare( "SELECT " "veh.*, us.user_name " "FROM veh_comments AS veh " "INNER JOIN " "users AS us " "ON us.id = veh.user_id " "WHERE " "veh_serial = ? " "ORDER BY " "comment_datetime DESC " ); my_query.addBindValue(id); my_query.exec(); return my_query; } void MainWindow::setUpDb() { _m_db = QSqlDatabase::addDatabase("QPSQL"); _m_db.setHostName("localhost"); _m_db.setDatabaseName("test"); _m_db.setUserName("postgres"); _m_db.setPassword("MyPostGresPSW0!"); if (!_m_db.open()) { qDebug() << "Error: Could not open database"; } }
After the "QStyledItemDelegate::setEditorData()", should I update the model, refresh it or something similar to save permanently the data to the SQL ?
-
@Andrea_Venturelli
Your posts are large and contain several questions. It's hard to keep up!I would start by sorting out the editability. Before you double-click to edit, print out the
flags()
of each item in the model. Do they all containItemIsEditable
? Then after double-clicking to edit, both then and after the edit is finished, print them all out again. Are you saying some/all of them lose theItemIsEditable
?doesn't set the new body text correctly as shown
I can't read the screenshot to see what you are saying. Is it just some sort of refresh issue, where the data has changed (automatically shown in the
QTableView
onto the SQL model) while it remains as-was on theQListView
item? Your view needs to know that the model data has changed and refresh accordingly, if it does not already do so automatically (as aQTableView
would).After the "QStyledItemDelegate::setEditorData()", should I update the model, refresh it or something similar to save permanently the data to the SQL ?
You have to start by deciding which QSqlTableModel::EditStrategy you are using/wish to use.
-
@JonB I didn't change nothing special beside adding the qDebug() line to print the flags and now all the items are editable and the EditorWidget show up correctly for all ... that's new.
I guess the "editing part is fixed now, but for simplicity I posted all the code on github here: https://github.com/aVenturelli-qt/CommentsListView?tab=readme-ov-file
-
You may have missed it but the way to use QSqlTableModel is to set the table you want to use on it rather than the query.