Call QAbstractTableModel setData method from QML - c++

I am trying to make a fully generic connection between the QML TableView and my C++ class that subclasses the QAbstractTableModel. So far I am able to read the data through data method, as this is done internally by the TableView module. From what I have read over SO however, I need to call setData myself on the QML side. The problem is, the function header looks as follows:
bool setData(const QModelIndex &index,
const QVariant &value,
int role = Qt::EditRole) override;
In order to call it, I need the QModelIndex, which I dont know how to obtain on the QML side. I would appreciate a QML example.
Edit: I have worked around this issue by wrapping the setData as follows:
Q_INVOKABLE bool setData(const int row,
const int column,
const QVariant& value);
bool CVarTableModel::setData(const int row,
const int column,
const QVariant& value)
{
return setData(index(row, column), value);
}
I can now call it directly on the QML side. The problem is, even though the actual setData is called now, the dataChanged signal doesnt make the QML TableView to update the cell... Is there anything else I am missing?

I can probably answer your edit. It seems like you might not be emitting dataChanged() signal in your setData function. This would explain why the view is not updated.
From QAbstractTableModel::setData() documentation:
The dataChanged() signal should be emitted if the data was successfully set.
Also, about your original question. You could use index method from the qml: model.setData(model.index(row,column), data) to avoid overriding setData.

Related

Save state of QTableWidget cell widget checkbox before setting its state

I have a QTableWidget, where one column is filled with custom checkboxes. Also, I have implemented an undo mechanic so that every change to the table can be undone. For the other item columns, where only text is stored, I basically achieve it in the following way:
Every time an item in the table is pressed (calling the itemPressed signal), I store the table data before the item editing starts using a function called saveOldState. After editing (and triggering an itemChanged signal), I push the actual widget content together with the old content onto a QUndoStack instance using a function called pushOnUndoStack.
Now I want to achieve a similar thing for the cell widgets. However, changing the checkbox state does not trigger itemChanged. Thus, I have to connect to the checkbox's stateChanged signal to save the new state:
QObject::connect(checkBox, &QCheckBox::stateChanged, this, [checkBox] {
pushOnUndoStack();
});
So, getting the newest table data is not that hard. However, I am struggling to find the right moment to save the data before the checkbox is set, because there is no similar variant for an itemPressed signal in case of a cell widget.
My question is: Is there a good alternative way to store the checkbox state immediately before the state is actually set? Currently, my only idea is to implement a custom mouse move event filter for the cell widget, which calls saveOldState the moment a user moves the mouse inside the cell widget's boundaries. But is there maybe a better way?
Chapter 1: the solution you cannot use
What I think is the correct way to address your question is a proxy model in charge of maintaining the undo stack. It does so by saving the model's data right before changing it.
Header:
class MyUndoModel : public QIdentityProxyModel
{
public:
MyUndoModel(QObject* parent = nullptr);
bool setData(const QModelIndex& index, const QVariant& data, int role) override;
bool restoreData(const QModelIndex& index, const QVariant& data, int role);
private:
void pushOnUndoStack(const QPersistentModelIndex& index, int role, const QVariant& value) const;
//QUndoStack undoStack;
};
Source:
bool MyUndoModel::setData(const QModelIndex& index, const QVariant& data, int role)
{
QVariant currentData = index.data(role);
bool result = QIdentityProxyModel::setData(index, data, role);
if (result) {
//If the source model accepted the change, push currentData to the undo stack.
pushOnUndoStack(QPersistentModelIndex(index), role, currentData );
}
return result;
}
bool MyUndoModel::restoreData(const QModelIndex& index, const QVariant& data, int role)
{
return QIdentityProxyModel::setData(index, data, role);
}
Note that we use QPersistentModelIndexes in a modified version of pushOnUndoStack (that I let you implement yourself). Also, I did not write how the stacked undo/redo commands should be processed, apart from calling restoreData. As long as you get the idea...
Chapter 2: where it fails for you
The above solution works regarless of the actual class of the source model ... except if working with QTableWidget and QTreeWidget.
What blocks this solution in the case of e.g. QTableWidget is its internal model (QTableModel).
You cannot substitute model of your QTableWidget to use MyUndoModel instead.
If you try, you will very quickly see your application crash.
You could in theory subclass QTableModel to perform the above substitution but I advise against it.Sample: myTableWidget->QTableView::setModel(new MyQTableModel);QTableModel is a private class in Qt and should not be used directly. I wish I knew why it was done this way.
Chapter 3:The alternative solution
Alternatively, subclassing QStyledItemDelegate could work for you. The design is not as clean, there are more ways to make a mistake when using it in your window but it essentially follows the same logic as the above proxy model.
class UndoItemDelegate : protected QStyledItemDelegate
{
public:
UndoItemDelegate(QUndoStack* undoStack, QObject* parent = nullptr);
//Importnt: we set setModelData as final.
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override final;
protected:
virtual QVariant valueFromEditor(QWidget *editor) const noexcept = 0;
virtual int roleFromEditor(QWidget *editor) const noexcept = 0;
private:
void pushOnUndoStack(const QPersistentModelIndex& index, int role, const QVariant& value) const;
//undoStack as a pointer makes it possible to share it across several delegates of the same view (or of multiple view)
mutable QUndoStack* undoStack;
};
The magic is in setModelData.
void UndoItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
auto role = roleFromEditor(editor);
QVariant currentData = index.data(role);
bool dataChanged = model->setData(index, valueFromEditor(editor), role);
if (dataChanged && undoStack) {
pushOnUndoStack(QPersistentModelIndex(index), role, currentData);
}
}
I kept the version with index (my habit) but you could use the pointers to QTableItem of course.
To be used (most likely in the constructor of your window):
ui->setupUi(this);
auto myDelegate = new MyUndoItemDelegateSubclass(&windowUndoStack, ui->myTableWidget);
ui->myTableWidget->setItemDelegate(myDelegate);
You will have to implement:
pushOnUndoStack (once).
roleFromEditor and valueFromEditor (for every subclass).
the processing of undo/redo commands.
Edit to address your comment.
I am going to assume you know how QAbstractIdemModel and subclasses work in a generic manner. To manipulate a checkState in the model of a QTableWidget, I recommend you create a UndoCheckboxDelegate subclass to implement/override the additional methods this way:
Header:
class UndoCheckboxDelegate : public UndoItemDelegate
{
public:
UndoCheckboxDelegate(QUndoStack* undoStack, QObject* parent = nullptr);
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
protected:
virtual QVariant valueFromEditor(QWidget *editor) const noexcept override;
virtual int roleFromEditor(QWidget *editor) const noexcept override;
};
Source:
UndoCheckboxDelegate::UndoCheckboxDelegate(QUndoStack* undoStack, QObject* parent)
: UndoItemDelegate(undoStack, parent)
{}
QWidget* UndoCheckboxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (index.isValid()) {
QCheckBox* control = new QCheckBox(parent);
control->setText(index.data(Qt::DisplayRole).toString());
control->setCheckState(index.data(Qt::CheckStateRole).value<Qt::CheckState>());
return control;
}
else
return nullptr;
}
QVariant UndoCheckboxDelegate::valueFromEditor(QWidget *editor) const noexcept
{
if (editor)
return static_cast<QCheckBox*>(editor)->checkState();
else
return QVariant();
}
int UndoCheckboxDelegate::roleFromEditor(QWidget * /* unused */) const noexcept
{
return Qt::CheckStateRole;
}
It may be only a starting point for you. Make sure it correctly fills the undo stack first; after that, you can tweak the behavior a bit.

QRegExpValidator with QTextEdit

Can QRegExpValidator be used with QTextEdit widget ?
I tried to implement through setValidator() and also set also the qtextedit as parent object. But its not working.
You should use
virtual QValidator::State QRegExpValidator::validate(QString & input, int & pos) const or bool QRegExp::exactMatch(const QString & str) const by yourself. It should not be hard, you just need to determine where to start validate.
You can do the following things
define another slot that will be called when textChanged() signal is
emitted
emit a signal with two parameters(data in qtextedit and
length of same data)
connect the validate() slot with the above slots

Automatically refreshing a QTableView when data changed

I have written a custom data model to be displayed with several QTableViews.
Technically, everything works fine: my views show the changes made from my model. My data model is editable, and the setData() method does emit the dataChanged() signal and returns true on successful edition.
However, my problem is that I have to move my mouse over a QTableView for it to show the actual change, while I would like all views to show the changes when they were made, without needing to interact with the views in order for them to be updated.
Any idea? Thanks,
It may be relevant to mention that I do not use the default Qt::EditRole role to edit data, but rather a custom enum value (named ActiveRole).
Here is what I am seeking: my data model contains properties on how to display data, used to generate style sheets that are fed to the viewS.
Thus, when altering the model, for each view, all its items are impacted, which is why the dataChanged() signal is sent with indices covering all cells.
I also tried to emit layoutChanged(), but it does not seem to change the behavior in my case.
Here is an excerpt of the setData() method:
bool DataModel::setData(QModelIndex const& idx, QVariant const& value, int role)
{
if (ActiveRole == role)
{
// Update data...
QModelIndex topLeft = index(0, 0);
QModelIndex bottomRight = index(rowCount() - 1, columnCount() - 1);
emit dataChanged(topLeft, bottomRight);
emit layoutChanged();
return true;
}
return false;
}
Here is a sample of the data() method:
QVariant DataModel::data(QModelIndex const& idx, int role) const
{
if (ActiveRole == role)
{
boost::uuids::uuid id;
return qVariantFromValue(id);
}
return QVariant();
}
And flags() does indicate an editable model:
Qt::ItemFlags DataModel::flags(QModelIndex const& idx) const
{
if (false == idx.isValid())
{
return Qt::ItemIsEditable;
}
return QAbstractTableModel::flags(idx) | Qt::ItemIsEditable;
}
I have a custom delegate, which relies heavily on this SO thread for overriding the paint and the sizeHint methods in order to draw a QTextDocument. Also, it provides the content of the ActiveRole to the editor in setEditorData, and calls DataMode::setData in setModelData:
void DataModelDelegate::setEditorData(QWidget* editor, QModelIndex const& idx) const
{
auto active = qVariantValue<boost::uuids::uuid>(idx.data(ActiveRole));
static_cast<DataModelEditor*>(editor)->setActive(active);
}
void DataModelDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, QModelIndex const& idx) const
{
auto active = static_cast<DataModelEditor*>(editor)->getActive();
model->setData(idx, qVariantFromValue(active), ActiveRole);
}
In the createEditor(), I plug a signal from the editor to a slot of my delegate for committing data:
QWidget* DataModelDelegate::createEditor(QWidget* parent, QStyleOptionViewItem const& option, QModelIndex const& idx) const
{
auto editor = new DataModelEditor(parent);
connect(editor, SIGNAL(activeItem()), this, SLOT(commitEditorData()));
return editor;
}
When clicking on an item, the editor triggers the activeItem signal; the connected slot commitEditorData in turn raises the commitData signal with the editor in argument.
So all my views use these custom delegate, editor, and data model. The view that I am interacting with does show the change immediately, but the other views need to have the mouse hovering over them to show changes as well.
I actually found the problem, which was that my other view was not properly notified of the data changes: my views each showed different portions of my data, so the other views needed to be notified of the dataChanged(), but for their own, proper, indices.
On a side note, I also had the problem of updating my views while my Qt application was not the active window in my window manager. The solution was to call repaint() on the main window.
I have met the same problem, and let me add a detailed explanation to the piwi's answers. If you change the data,and what to update the single or several columns(or rows,depending on your requirement), you should emit a set of index for topleft to bottomright.For example,if you have a table like below:
and, now you have changed some data, and want to update the cell row 1, column 1-2, then you should emit signal dataChange
emit datachange(index(1,1),index(1,2));
Are you calling the setData()? Is the dataChanged() signal really emitted? Connect some debug logging slot to it. I dare to speculate that this is very similar problem to yours:
http://www.qtcentre.org/threads/18388-Refreshing-a-QTableView-when-QAbstractTableModel-changes?s=fd88b7c4e59f4487a5457db551f3df2c

How do I keep my QAbstractTableModel in sync with my data store?

In my app, I have a class for keeping a list of items:
class Database : public QObject
{
Q_OBJECT
public:
Database(QObject *parent, const QString &name);
const Entry& item(int idx) const { Q_ASSERT(idx < itemCount()); return _items.at(idx); }
const QString& name() const { return _name; }
int itemCount() const { return _items.size(); }
bool addItem(const Entry &item);
bool addItems(const Database *source, const QList<int> &idxs);
bool updateItem(int idx, const Entry &updated);
void removeItem(int idx);
void removeItems(const QList<int> &idxs);
private:
QList<Entry> _items;
signals:
void itemsRemoved(int start, int count);
void itemsAdded(int count);
void itemChanged(int index);
void countUpdate();
};
The item manipulation functions (add, update, remove) emit the corresponding signals when done (items added, changed, removed). I have a list of such Database's and a QTableView for displaying their contents. I also have one object of a custom, QAbstractTableModel-derived model class, which can be made to point to (and display) a different Database when needed:
class DatabaseModel : public QAbstractTableModel
{
Q_OBJECT
public:
DatabaseModel(QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const { return _data->itemCount(); }
int columnCount(const QModelIndex &parent = QModelIndex()) const { return 5; };
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const = 0;
void setDatabase(const Database *data);
{
beginResetModel();
_data = data;
endResetModel();
}
protected:
const Database *_data;
};
I have a problem with making the model reflect the changes to its current Database. Before, I got it to work by issuing a model reset every time something changed in the Database (triggered by a signal from the Database to the DatabaseModel), but decided that was overkill. Now I have no idea how to connect Database and the model correctly.
Connecting the Database signals to the model and make the model emit dataChanged() doesn't work because the number of items in Database (and hence the model's rows) is changing. There are signals called rowsInserted() and rowsRemoved() in QAbstractTableModel, but the docs say they can't be used in custom classes. There are virtual functions to be reimplemented called removeRows() and insertRows(), but the docs say I must call begin(Remove|Insert)Rows() and end(Remove|Insert)Rows() inside them, which leads to two problems:
begin...Rows() needs a QModelIndex 'parent' parameter, for which I've no idea what to use
EDIT: Actually it doesnt matter, now I'm passing QModelIndex() for this. This is used by QAbstractTreeModel to identify a parent node in a tree and is apparently not necessary for table models.
the docs say these functions need to be called before changing the underlying data store
How do I make the model keep in sync with the database? Thanks!
I think I see your problem.
One the one side you're doing the right thing and trying to keep the data seperate from the model, on the other hand your data isn't aware of the model itself.
There is a reason why you should call begin...Rows() before changing the data and end...Rows() afterwards. Namely the QPersistentModelIndex. Usually you're not supposed to hort QModelIndex objects, but the persistent index is ment to be saved and kept. The model must guarantee its validity. Looking at the code of those begin...Rows() methods it is mainly about those persistent indices.
You have several choices.
a) If you're positivly sure you won't be using persistent indices you could just implement a private slot in your model which listens to a sort of update signal from your data source. This slot would simply call begin...Rows() and end...Rows() with nothing in between. It's not "clean" but it'll work.
b) You could implement more signals in your data source, one that signals the beginning of a data change (removal or adding of a row for example) and one that signals the end of said operation. Of course that would significantly increasy the size of your code.
c) You could make your DataBase class a friend in the model and call the begin... end... methods from within your datasource, but then DataBase would have to be aware of the model.
d) You could rethink the concept. From what I can grasp you're using the DataBase class as a data storage for your model and as an interface for other parts of your code, right?
Wouldn't it be easier to use custom items with methods that operate on the model itself and thus avoid the trouble? I've done my fair share of those so I could give you the code if need be.
Hopefully that helps.
Best regards

How do I detect row selections in QListView <- > QAbstractListModel with Item Delegate?

It seems there is zero built-in selection support with my choice of QListView -> QAbstractListModel. Do I have to write everything from scratch? the catching of a selection event in the UI, the marking of the model item as selected, etc? It seems there is no out-of-the-box support for this.
the weird thing is that there is a QItemSelectionModel that does support this, but you cannot use it with QListView as it’s not derived from QAbstract….
Should my model class use multiple inheritance to inherit both from QItemSelectionModel and QAbstractListModel? Otherwise I don’t see how I can avoid having to re-writing this functionality myself.
My final goal is for the delegate that draws my items to know if the item is selected, both in the paint and the sizeHint function.
QListView is derived from QAbstractItemView, which has a method to get the selection model:
QItemSelectionModel *selectionModel = myView->selectionModel();
This method returns a pointer to the selection model, which is long-lived, i.e., you can save the pointer, connect to its signals, etc.
The answer given by Daniel is correct, but it is better to show it with an example suitable for beginners:
class MyCustomModel : public QAbstractListModel
{
Q_OBJECT
public:
ImageCollectionModel(QObject *parent, MyCustomCollection *data);
: QObject(parent)
, m_myData(data)
{
}
public slots:
void onSelectedItemsChanged(QItemSelection selected, QItemSelection deselected)
{
// Here is where your model receives the notification on what items are currently
// selected and deselected
if (!selected.empty())
{
int index = selected.first().indexes().first().row();
emit mySelectedItemChanged(m_myData->at(index));
}
}
signals:
void mySelectedItemChanged(MyCustomItem item);
private:
MyCustomCollection *m_myData;
// QAbstractItemModel interface
public:
int rowCount(const QModelIndex &) const override;
QVariant data(const QModelIndex &index, int role) const override;
};
When you pass your custom model to the QListView, that's a great opportunity to connect it:
ui->myListView->setModel(m_myModel);
connect(ui->myListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
m_myModel, SLOT(onSelectedItemsChanged(QItemSelection, QItemSelection)));