How to remove all child items of the root item in tree view - qt

I want to remove all the tree items in the tree view of the invisible Root Item.
Currently this is what my workflow is
QModelIndex index = treeView->rootIndex();
QAbstractItemModel *model = treeView->model();
TreeModel *myModel = qobject_cast<TreeModel*>(model);
TreeItem* itm = myModel->getItem(index);
itm->removeChildren(0, itm->childCount());
bool TreeItem::removeChildren(int position, int count)
{
if (position < 0 || position > childItems.count())
return false;
for (int row = 0; row < count; ++row)
{
delete childItems.takeAt(position);
}
return true;
}
Though i am able to delete all the items in the tree view it seems as if the Tree model indexes are not getting updated.
After deleting all the Tree items if i try to add a new item the application crashes.

You need delete your elements in between these calls.
beginResetModel();
and
endResetModel()

Related

How to apply Filter for Tree which is developed using QStandardItemModel

Implemented Tree using QStandardItemModel.. like below
QStandardItem *americaItem = new QStandardItem("America");
QStandardItem *mexicoItem = new QStandardItem("Canada");
QStandardItem *usaItem = new QStandardItem("USA");
QStandardItem *bostonItem = new QStandardItem("Boston");
QStandardItem *europeItem = new QStandardItem("Europe");
QStandardItem *italyItem = new QStandardItem("Italy");
QStandardItem *romeItem = new QStandardItem("Rome");
QStandardItem *veronaItem = new QStandardItem("Verona");
//building up the hierarchy
rootNode-> appendRow(americaItem);
rootNode-> appendRow(europeItem);
americaItem-> appendRow(mexicoItem);
americaItem-> appendRow(usaItem);
usaItem-> appendRow(bostonItem);
europeItem-> appendRow(italyItem);
italyItem-> appendRow(romeItem);
italyItem-> appendRow(veronaItem);
//register the model
treeView->setModel(standardModel);
So now Im unable to do search operation, using that QFilterProxyModel im able to search only parent data.. Any suggestion to search parent and child rows too..(using filterAcceptsRow or any other)
Implemented search filter like this:
Derived a class from QSortFilterProxyModel
Overrided the filterAcceptsRow method
bool FilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
// check the current item
bool result = QSortFilterProxyModel::filterAcceptsRow(source_row,source_parent);
QModelIndex currntIndex = sourceModel()->index(source_row, 0, source_parent);
if (sourceModel()->hasChildren(currntIndex))
{
// if it has sub items
for (int i = 0; i < sourceModel()->rowCount(currntIndex) && !result; ++i)
{
// keep the parent if a children is shown
result = result || filterAcceptsRow(i, currntIndex);
}
}
return result;
}
mFilterProxyModel->setFilterRegExp(ui->mLeSearchFilter->text());

How to iterate through all indexes in Tree Model

I want to iterate through all indexes in the Tree model as shown in the image.
The function that I have written gives stack overflow error.
void iterate(const QModelIndex & index, const QAbstractItemModel * model)
{
if (index.isValid())
PrintData( index );
if (!model->hasChildren(index) || (index.flags() & Qt::ItemNeverHasChildren))
{
return;
}
auto rows = model->rowCount();
for (int i = 0; i < rows; ++i)
iterate(model->index(i, 0, index), model);
}
Pass the current index as parameter of QAbstractItemModel::rowCount() to get its number of rows. Otherwise, you will get the number of root items in your tree.
So, replace auto rows = model->rowCount(); by auto rows = model->rowCount(index);

Keep row selected in QTableView

I am working on a program to view and edit records in a file. It features a QTableView that displays all records, a QLineEdit to search for records, and some labels that display the details of the selected record:
There is a QAbstractTableModel class that holds the data and a QSortFilterProxyModel class that helps filtering the rows in the QTableView.
Searching and filtering works fine. Typing text in the search box immediately filters the list of records. But there are two things I cannot get to work:
if the list is not empty, I want one item to be selected/current always
the selected/current item must be brought into view when typing in the search box
For example, when I type "tesla", the list will be empty since no item matches. But as soon as I backspace to "te", the "Forester" matches and I want it to be selected. Second example: when (after starting the program) I type "f" the list is narrowed down to 8 items and "Pacifica" is selected. When I erase the "f", the Pacifica is still selected but no longer in the visible part of the list.
I have posted the full source code of this on Pastie, and here are some (hopefully) relevant snippets.
void MainWindow::on_lineEditSearch_textChanged(const QString & text)
{
itemProxy->setFilterFixedString(text);
updateStatusBar();
}
void MainWindow::currentRowChangedSlot(QModelIndex const & current, QModelIndex const & /*previous*/)
{
Car * car = 0;
if (current.isValid())
{
QModelIndex sibling = current.sibling(current.row(), COLUMN_THIS);
QVariant variant = itemProxy->data(sibling);
car = static_cast<Car *> (variant.value<void *> ());
}
updateCarMake(car);
updateCarModel(car);
}
MainWindow::MainWindow(QWidget * parent, CarItemModel * itemModel, CarSortFilterProxyModel * itemProxy) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
this->itemModel = itemModel;
this->itemProxy = itemProxy;
ui->setupUi(this);
setupStatusBar();
ui->tableView->setModel(itemProxy);
ui->tableView->setColumnHidden(COLUMN_THIS, true);
QItemSelectionModel * selectionModel = ui->tableView->selectionModel();
connect(selectionModel, SIGNAL(currentRowChanged(QModelIndex const &, QModelIndex const &)),
this, SLOT(currentRowChangedSlot(QModelIndex const &, QModelIndex const &)));
connect(selectionModel, SIGNAL(selectionChanged(QItemSelection const &, QItemSelection const &)),
this, SLOT(selectionChangedSlot(QItemSelection const &, QItemSelection const &)));
ui->tableView->selectRow(0);
ui->lineEditSearch->setFocus();
updateStatusBar();
}
<widget class="QTableView" name="tableView">
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
</widget>
So, my question is: how can I make sure an item is always selected and in the visible part of the list (unless the user is scrolling, of course)?
Here's what I did to
always have an item selected, and
have the selected item visible when searching
The solution is even a bit fancier since when going from no visible items to some visible items the most recently selected item will be selected instead of just the first item.
First, I added a QModelIndex lastModelIndex; private member to the MainWindow class, and set it in the SelectionChanged slot. Note that the model index is stored and not the proxy index.
void MainWindow::selectionChangedSlot(QItemSelection const & selected, QItemSelection const & /*deselected*/)
{
if (selected.count() > 0)
{
QModelIndex index = selected.indexes().first();
QModelIndex modelIndex = itemProxy->mapToSource(index);
lastModelIndex = modelIndex;
}
}
Next, I added two methods: ensureSelected() ...
void MainWindow::ensureSelected(QItemSelectionModel * selectionModel, int const proxyCount)
{
if (selectionModel->hasSelection())
{
// an item is currently selected - don't have to do anything
}
else if (proxyCount == 1)
{
// no item is currently selected, but there is exactly one item in the list - select it
QModelIndex proxyIndex = itemProxy->index(0, 0);
selectionModel->setCurrentIndex(proxyIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
else if (proxyCount > 1)
{
// no item is currently selected, but there are several items in the list
QModelIndex proxyIndex; // !isValid
if (lastModelIndex.isValid())
{
// there's a most recently selected item - compute its index in the list
proxyIndex = itemProxy->mapFromSource(lastModelIndex);
}
if (proxyIndex.isValid())
{
// the most recently selected item is in the list - select it
proxyIndex = proxyIndex.sibling(proxyIndex.row(), COLUMN_THIS);
}
else
{
// there's no most recently selected item or it is no longer in the list - select the first item
proxyIndex = itemProxy->index(0, 0);
}
selectionModel->setCurrentIndex(proxyIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
else
{
// There are no items in the list - cannot select anything.
}
}
... and ensureVisible():
void MainWindow::ensureVisible(QItemSelectionModel * selectionModel)
{
if (selectionModel->hasSelection())
{
const QModelIndex index = ui->tableView->currentIndex();
ui->tableView->scrollTo(index);
ui->tableView->selectRow(index.row());
ui->tableView->scrollTo(index);
}
}
Weird as it may seem, I have to call scrollTo() twice, or the tableView won't scroll.
These new methods are called from on_lineEditSearch_textChanged() like so:
void MainWindow::on_lineEditSearch_textChanged(const QString & text)
{
itemProxy->setFilterFixedString(text);
QItemSelectionModel * selectionModel = ui->tableView->selectionModel();
int modelCount = itemModel->rowCount(); // number of items in the model
int proxyCount = itemProxy->rowCount(); // number of items in tableview
ensureSelected(selectionModel, proxyCount);
ensureVisible(selectionModel);
updateStatusBar();
}
Please find the updated and complete source code on Pastie.
Handle selection change signal and connect it to your custom slot:
QSortFilterProxyModel *model = new QSortFilterProxyModel(this);
ui->tableView->setModel(model);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
Every time, you table change the current selection the app should select the first item in the model:
void MainWindow::selectionChanged(QItemSelection selected, QItemSelection deselected) {
// Use this
const int rows = ui->tableView->selectionModel()->selectedRows().size();
// or
const int rowCount = selected.size();
// Lets select the first item if there are some items availables
if (rowCount < 1) {
const int availableItems = ui->tableView->model()->rowCount();
if (availableItems > 0) {
const QModelIndex index = ui->tableView->model()->index(0,0);
ui->tableView->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
}
}
}
By this way, you should have at least one item selected.

qtablewidget selectedItems gives empty list

I have a qtablewidget with one column with a widget and others with data. The only column with widget is shown and all other columns are hidden.
foreach (BillHeader *billHeader, billHeaderList)
{
m_pBillTable->insertRow(i);
itemWidget = new LookupItem;
itemWidget->setImage(1);
...
m_pBillTable->setCellWidget(i, 0, itemWidget);
tableItem = new QTableWidgetItem(billHeader->billNumber);
tableItem->setTextAlignment(Qt::AlignCenter);
m_pBillTable->setItem(i, 1, tableItem);
...
m_pBillTable->hideColumn(1);
...
I have a signal slot connected as below:
connect(m_pOkButton, SIGNAL(clicked()), this, SLOT(handleOkClick()));
when ok button click i try to get the selected item and get data from the widget set to it
void OrderLookup::handleOkClick()
{
qDebug()<<Q_FUNC_INFO<<"Invoked";
QList<QTableWidgetItem*> itemList = m_pBillTable->selectedItems();
qDebug()<<Q_FUNC_INFO<<itemList.count();
if (!itemList.isEmpty())
{
int row = itemList.at(0)->row();
qDebug()<<Q_FUNC_INFO<<row;
LookupItem *item = (LookupItem*)m_pBillTable->cellWidget(row, 0);
if (NULL != item)
{
QString billNumber = item->getBillNumber();
emit orderLookupComplete(billNumber);
accept();
}
}
qDebug()<<Q_FUNC_INFO<<"Exits";
}
But i am getting the list count as zero.
The row is getting selected and gets highlighted.
I’ve set some properties to table widget as below:
m_pBillTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_pBillTable->setSelectionBehavior(QAbstractItemView::SelectRows);
m_pBillTable->setSelectionMode(QAbstractItemView::SingleSelection);
m_pBillTable->setFocusPolicy(Qt::NoFocus);
Please can someone help me to know why list count is empty..
The issue got solved ..
QItemSelectionModel *itemModel = m_pBillTable->selectionModel();
QModelIndexList indexList = itemModel->selectedRows();
qDebug()<<Q_FUNC_INFO<<"IndexList Count"<<indexList.count();
if (!indexList.isEmpty())
{
int row = indexList.at(0).row();

HowTo find Subitem in QAbstractItemModel and QTreeView class?

Question: how to find sub item, in a QTreeView loaded QAbstractItemModel model with model->match() method?
Problem: model->match() can't find sub items, wtf?!
Here is the example:
As you can see from the picture, I'm trying to expand Layouts sub item with this code:
void Dialog::restoreState(void)
{
// get list
QSettings settings("settings.ini", QSettings::IniFormat);
settings.beginGroup("MainWindow");
QStringList List = settings.value("ExpandedItems").toStringList();
settings.endGroup();
foreach (QString item, List)
{
if (item.contains('|'))
item = item.split('|').last();
// search `item` text in model
QModelIndexList Items = model->match(model->index(0, 0), Qt::DisplayRole, QVariant::fromValue(item));
if (!Items.isEmpty())
{
// Information: with this code, expands ONLY first level in QTreeView
view->setExpanded(Items.first(), true);
}
}
}
Where settings.ini file contains:
[MainWindow]
ExpandedItems=Using Containers, Connection Editing Mode, Form Editing Mode, Form Editing Mode|Layouts
PS: root items successfully expands on start!
Here is the solution:
QModelIndexList Items = model->match(
model->index(0, 0),
Qt::DisplayRole,
QVariant::fromValue(item),
2, // look *
Qt::MatchRecursive); // look *
* Without that argument match() function searches only 1 level
My working example on QTreeView.
QModelIndexList Indexes = this->ui->treeView->selectionModel()->selectedIndexes();
if(Indexes.count() > 0)
{
QStandardItemModel *am = (QStandardItemModel*)this->ui->treeView->model();
QStack<QModelIndex> mis;
QModelIndex mi = Indexes.at(0);
while(mi.isValid())
{
mis.push(mi);
mi = mi.parent();
}
QStandardItem *si;
bool FirstTime = true;
while (!mis.isEmpty())
{
mi = mis.pop();
if(FirstTime)
{
FirstTime = false;
si = am->item(mi.row());
}
else
{
si = si->child(mi.row());
}
}
// "si" - is selected item
}
Wanted to add to the answer that #mosg gave
The forth parameter is actually the hits parameters.
It decides ho many matches one wants to return.
For all matches specify -1 as can be seen
here:
QModelIndexList Items = model->match(
model->index(0, 0),
Qt::DisplayRole,
QVariant::fromValue(item),
-1, // any number of hits
Qt::MatchRecursive); // look *

Resources