QAbstractTableModel empty last row, without sorting - c++

I have my own table model (DragDropTableModel) subclassed from QAbstractTableModel. Inside it I would like for the last row to remain always empty.
I implement it by adding insertRows() into setData() function:
bool DragDropTableModel :: setData (const QModelIndex &index, const QVariant &value, int role)
{
...
if (role == Qt::EditRole)
{
...
if (row == this->rowCount() - 1)
insertRows(this->rowCount(), 1);
}
}
After that I have QSortFilterProxyModel installed on it. The problem is: when I do sorting, the last row is also sorted. But I want to make it not obeying sorting and to stand on the same last position. So no matter the sorting order is (Ascending or Descending) the last row should always be empty.
How to make it? May be I should use another approach to realize "making empty row" in my model?

Thanks, murison. Your idea worked.
I set up a value "EMPTY_ROW" for Qt::UserRole for the items of empty row. After that I reimplemented lessThan() method in QSortFilterProxyModel:
bool MySortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
if (left.data(Qt::UserRole) == "EMPTY_ROW")
return (this->sortOrder() == Qt::DescendingOrder);
else if (right.data(Qt::UserRole) == "EMPTY_ROW")
return (this->sortOrder() == Qt::AscendingOrder);
else
return QSortFilterProxyModel::lessThan(left, right);
}
So this row always appears in the bottom of the table after sorting.
Also it's nescesary not to forget to clear Qt::UserRole when this empty row is filled with data.

Related

Why can't you use setData() to set background color of a Cell in QTreeView?

I'm using the following code to try to change the background color of a cell at a given QModelIndex.
ui->TreeView->model()->setData(index, QVariant(QBrush (QColor(Qt::green))) , Qt::BackgroundRole);
where index is given by the dataChanged() signal.
This isn't working. Any ideas why?
Here's my reimplemented setData function.
bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
TreeItem *item = getItem(index); //gets item a given index
bool result = item->setData(index.column(), value);
if (result)
emit dataChanged(index, index);
return result;
}
And here is the setData method for the underlying item:
bool TreeItem::setData(int column, const QVariant &value)
{
if (column < 0 || column >= itemData.size())
return false;
itemData[column] = value;
return true;
}
Apologies for the vague question. I've managed to solve it by myself so I will post here in case anyone is ever stuck on a similar issue.
The problem for me was that I hadn't reimplemented QAbstractItemView's data() method to account for the new role.
QVariant TreeModel::data(const QModelIndex &index, int role) const
{
TreeItem *item = getItem(index);
if (role == Qt::BackgroundRole)
return item->data(index.column());
//and so on...
AFAIK the data() method gives the treeview the data out of the model that it needs to present. Within this method I hadn't accounted for the case when role == Qt::BackgroundRole so the view was never given the appropriate information out of the model.

QT Multiple item selection from a list of files and folders

I'm developing a Qt C++ application in Unix and I've been trying to do something similar to what this image shows:
As you can see, there is a list of files and folders and a user can select multiple of them (if a folder is selected, all childs also get selected). I don't really care if the folder/file icons are shown.
I was able to create a list of QDir which stores all the files and folders paths given a root path. The problem is that I don't really know which widgets to use to design the selection panel.
By the way, the lis of QDir is a vector, but it can be easily modified to anything else.
Thanks!
You can try to make proxy model for QFileSystemModel, override flags() with Qt::ItemIsUserCheckable, override setData() and apply the model to QTreeView. Full example can be found at https://github.com/em2er/filesysmodel. This code is just a concept, i have not tested it thoroughly, but you can take some ideas from it. It will look smth like on the screenshot:
.
Also you can combine it with Merged Proxy Model to display multiple starting paths at one view.
You might want to consider the QTreeWidget, or it's a tad more advanced version - QTreeView and an appropriate data model.
As some users suggested, I ended up using QFileSystemModel. I'm gonna give a full description of how I implemented it, in case someone else comes up with this problem and needs a clear response.
First of all, a QFileSystemModel is a file tree without checkboxes, to add them, a new class which extends QFileSystemModel and at least 3 methods must be overriden.
class FileSelector : public QFileSystemModel
{
public:
FileSelector(const char *rootPath, QObject *parent = nullptr);
~FileSelector();
bool setData(const QModelIndex& index, const QVariant& value, int role);
Qt::ItemFlags flags(const QModelIndex& index) const;
QVariant data(const QModelIndex& index, int role) const;
private:
QObject *parent_;
/* checklist_ stores all the elements which have been marked as checked */
QSet<QPersistentModelIndex> checklist_;
};
When creating the model a flag, to indicate that it should have a checkable box, must be set. This is why we will use the flags function:
Qt::ItemFlags FileSelector::flags(const QModelIndex& index) const
{
return QFileSystemModel::flags(index) | Qt::ItemIsUserCheckable;
}
When a click is made in the checkbox, the method setData will be called, with the index of the element that was clicked (not the checkbox itself, but the :
bool FileSelector::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (role == Qt::CheckStateRole && index.column() == 0) {
QModelIndexList list;
getAllChildren(index, list); // this function gets all children
// given the index and saves them into list (also saves index in the head)
if(value == Qt::Checked)
{
for(int i = 0; i < list.size(); i++)
{
checklist_.insert(list[i]);
// signals that a change has been made
emit dataChanged(list[i], list[i]);
}
}
else if(value == Qt::Unchecked)
{
for(int i = 0; i < list.size(); i++)
{
checklist_.remove(list[i]);
emit dataChanged(list[i], list[i]);
}
}
return true;
}
return QFileSystemModel::setData(index, value, role);
}
When dataChanged is signaled or you open a new path of the tree, the data function will be called. Here you have to make sure to only display the checkbox at the first column (next to the filename), and to retrieve the state of the checkbox, to mark it as checked/unchecked.
QVariant FileSelector::data(const QModelIndex& index, int role) const
{
if (role == Qt::CheckStateRole && index.column() == 0) {
if(checklist_.contains(index)) return Qt::Checked;
else return Qt::Unchecked;
}
return QFileSystemModel::data(index, role);
}
The only thing I was not able to accomplish was getting all childs, since the folders must be open to retrieve the childs. So a closed folder won't have any child until you open it.
Hope this can help someone who has the same problem as I did!

Qt checkboxes in QTableView

I'm using this code to query sqlite and put the results in a QTableView.
//MainWindow.cpp
void MainWindow::on_pushButton_clicked()
{
QSqlQueryModel * modal=new QSqlQueryModel();
connOpen();
QSqlQuery* qry=new QSqlQuery(mydb);
qry->prepare("select * from database");
qry->exec();
modal->setQuery(*qry);
//from stack
modal->insertColumn(0);
ui->tableView->setModel(modal);
//from stack
ui->tableView->resizeColumnsToContents();
int p;
for(p=0; p<modal->rowCount(); p++)
{
ui->tableView->setIndexWidget(modal->index(p,0),new QCheckBox());
}
connClose();
qDebug() <<(modal->rowCount());
}
I've seen several examples of the web for adding checkboxes to a column, but I'm not quite sure what to use for my simple example.
This answer suggests a few lines that doesn't seem standard.
There are more examples like this and this one that appear to outline what I need, but it's unclear to where you place the code.
What I intend to do is to have column 1 checkable. On next btn press, If checked those rows of data get written to a file.
I still need to understand how to loop thru the selected data, or perhaps I need to get the ids of the checked rows and do another query.
Questions:
How do you add 1 column of editable checkboxes to QTableView?
How do you loop through values in the QTableView data, so values of the checked rows can be accessed?
How do you check all/none?
I think the best way to have a column of checkable cells is to create your item model, e.g. by subclassing the QSqlQueryModel.
You must reimplement the flags() method to make checkable the cells.
Also you need to reimplement the data() method to return the check state and the setData() method and to set the check state. You must implement your own logic to keep track of the check state of every rows (e.g. using an array of Qt::CheckState that you must initialize and resize when the model data changes).
Yuo can start with something like this:
class MyModel : public QSqlQueryModel
{
public:
Qt::ItemFlags flags(const QModelIndex & index) const
{
if(index.column() == 0)
return QSqlQueryModel::flags(index) | Qt::ItemIsUserCheckable;
return QSqlQueryModel::flags(index);
}
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const
{
if(index.column() == 0 && role == Qt::CheckStateRole)
{
//implement your logic to return the check state
//....
}
else
return QSqlQueryModel::data(index, role);
}
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole)
{
if(index.column() == 0 && role == Qt::CheckStateRole)
{
//implement your logic to set the check state
//....
}
else
QSqlQueryModel::setData(index, value, role);
}
};
Se also:
Model Subclassing
QAbstractItemModel documentation

QTreeView: hierarchical context for multi-level columns

I'm looking for a better way to display multi-level hierarchical data in a tree where the meaning of each column changes depending on the level in the tree.
I am using QTreeView and QAbstractItemModel to display my model data.
Each model row has a different number of columns and different column names depending on its level in the hierarchy.
In order to give context to the data displayed in the tree, I need to have column headers for each level in the hierarchy.
The problem is that QTreeView only has 1 set of column headers.
Current method
At the moment I'm changing the headers each time the selected row changes.
I do this by connecting to the tree view's selectionModel, and emitting a signal with the new QModelIndex each time the selection changes
void Window::slotOnSelectionChanged(const QItemSelection& new_selection, const QItemSelection& old_selection)
{
QItemSelectionModel* selection_model = _view->selectionModel();
QModelIndex index = selection_model->currentIndex();
if (index.isValid())
emit selectedIndexChanged(index);
}
In my model I connect to this signal, and when its fires, store the selected row, and force a column header update
void Model::slotOnSelectedIndexChanged(QModelIndex index)
{
assert(index.isValid());
_selected_row = modelRow(index);
emit headerDataChanged(Qt::Horizontal, 0, _root->numColumns());
}
In the QAbstrateItemModel::headerData callback I then use selected_row to get the header for the currently selected row
QVariant Model::headerData(int i, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole)
{
switch (orientation)
{
case Qt::Horizontal:
return QVariant(_selected_row->header(i));
...
Result
The result can be seen below - notice how the column headers change as the selected row changes.
Problem
It's not immediately obvious by just looking at the view what each datum is, and therefore the user is required to change rows in order to see what each column actually means.
What I'd like is to have some sort of embedded column header row, 1 per level in the hierarchy.
Something like this:
Questions
Is this possible?
If there is a better way to give context to the data in the tree, please do offer a suggestion.
At the suggestion of #Kuba Ober I added an extra row at position 0 in each hierarchy of the tree. It has no children.
The model is then configured to special case for index.row() == 0, knowing that this row is a header row rather than a data row.
eg: in Model::flags the header row is not editable
Qt::ItemFlags Model::flags(const QModelIndex& index) const
{
Qt::ItemFlags item_flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
// header row is not editable
if (index.row() != 0)
item_flags |= Qt::ItemIsEditable;
return item_flags;
}
I now return empty strings for headerData as the headers are in the tree itself
QVariant Model::headerData(int i, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole)
{
switch (orientation)
{
case Qt::Horizontal:
return QVariant(); // no column header, it's already in the tree
...
I also change the background color for the header so it stands out
QVariant Model::data(const QModelIndex& index, int role) const
{
switch (role)
{
case Qt::BackgroundColorRole:
if (index.row() == 0) // header row
return QColor(Qt::darkGray);
break;
...
The result is almost exactly what I was looking for

QTableView and unique IDs

I'm new to Qt and coming from C# .Net. I am trying to replicate a fairly simple program I wrote in C# in Qt as a learning tool. I have a data model that inherits QAbstractTableModel and implements:
rowCount,
columnCount,
data,
setData,
headerData
flags
My data structure is a map
std::map<int, CBDataRow>
So the idea was that each row would have a unique int ID and a struct containing the rest of the row information.
What I am stuck on now is how to update my data model when the user makes an edit in the QTableView object. The setData function does get called. Here it is:
bool CBDatabaseModel::setData(const QModelIndex &index, const QVariant &value, int role) {
bool success = false;
if(role == Qt::EditRole) {
success = m_data.UpdateRow(index, value);
}
if(success) {
emit dataChanged(index, index);
return true;
} else {
return false;
}
}
Now you see that the UpdateRow() function gets called here on an edit. That function should find the unique id in the map and update the appropriate members of its CBDataRow struct. My problem is that I have no idea how to get the unique ID out of the QModelIndex object that gets passed into the edit function.
For example:
User edits the "CB Name" cell of row 3. The data in row three has a unique ID of 100. That value of 100 is in the QTableView in a hidden column, column index 0. So what I need to do is simply:
(Psuedo code)
it = m_data.find(unique_id);
it->second.cb_name = value.toString();
Since the user was editing column 1, how do i find the unique ID that is contained in column 0?
I would recommend to reimplement index() method of your model and there create indexes by using the call createIndex(row,col, unique_id);
Then in any place where you got QModelIndex, you can always extract unique_id = model_index.internalId();
In my opinion you can store your data in an array and index your element simply accessing through index.row():
QVector<CBDataRow> m_data;
....
bool CBDatabaseModel::setData(const QModelIndex &index, const QVariant &value, int role) {
bool success = false;
if(role == Qt::EditRole && index.row() < m_data.size()) {
success = m_data.at(index.row()).UpdateRow(index.column(), value);
}
if(success) {
emit dataChanged(index, index);
return true;
} else {
return false;
}
}
if you are worrying about element sorting you can derive your model from a QSortFilterProxyModel (instead of a QAbstractTableModel) and then reimplement
bool CBDatabaseModel::lessThan(const QModelIndex &left,
const QModelIndex &right) const
without define a internal id by yourself.
I hope this can help you.