Qt - Expand QTreeView on single click?
While double-clicking the text of a QTreeView expands the children, a single-click does not. The icon defined in the CSS (and placed to left of text开发者_运维百科) expands the children on a single-click, though. How do I make it so a single-click (or touch event) of the text will expand the children?
bookTreeView->setModel(standardModel);
bookTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
bookTreeView->setWordWrap(true);
bookTreeView->sizeHint();
//bookTreeView->mousePressEvent(QMouseEvent());
bookTreeView->setTextElideMode(Qt::ElideNone);
bookTreeView->setExpandsOnDoubleClick(true);
bookTreeView->setUniformRowHeights(true);
bookTreeView->setHeaderHidden(true);
bookTreeView->setStyleSheet("QTreeView { font-size: 27px; show-decoration-selected: 0; } QTreeView::branch:has-siblings:!adjoins-item { border-image: none; } QTreeView::branch:has-siblings:adjoins-item { border-image: none; } QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: none;} QTreeView::branch:has-children:!has-siblings:closed, QTreeView::branch:closed:has-children:has-siblings { border-image: none; image: url(':images/images/right_arrow.png'); } QTreeView::branch:open:has-children:!has-siblings, QTreeView::branch:open:has-children:has-siblings { border-image: none; image: url(':images/images/down_arrow.png'); } ");
Something along the lines of
QObject::connect(
tree, SIGNAL(clicked(const QModelIndex &)),
tree, SLOT(expand(const QModelIndex &))
);
The clicked
signal might not do what you want. You can also have a look at the currentChanged
signal, which might be what you want. I've never used Qt in a mobile context :)
Same Grund answer, but I add close on the click if it already open.
QObject::connect(
tree, SIGNAL(clicked(const QModelIndex &)),
this, SLOT(expandItem(const QModelIndex &))
);
void MainWindow::expandItem(const QModelIndex &index)
{
tree->isExpanded(index)? tree->collapse(index) : tree->expand(index);
}
in mainwindow.h:
private slots:
void expandItem(const QModelIndex &index)
Did you tried to turn off double click expansion?
bookTreeView->setExpandsOnDoubleClick(false);
ui.tree_view->setExpandsOnDoubleClick(false);
QObject::connect(ui.tree_view, &QTreeView::clicked, [this]() {
if (ui.tree_view->isExpanded(ui.tree_view->currentIndex())) {
ui.tree_view->collapse(ui.tree_view->currentIndex());
}else{
ui.tree_view->expand(ui.tree_view->currentIndex());
}
});
Tested on the Visual Studio version of Qt.
An alternate method that opens and closes on a single click.
This method has no extra function required as it uses a lambda.
Place this in your constructor to run.
note: I set expands on double click to false because logically when one click expands, two clicks will undo the expand that the first one did.
That option makes the flow smoother and more consistent.
精彩评论