PDA

View Full Version : QTreeWidget takeChildren() without removing



franco.amato
20th January 2022, 16:17
Hi community,
I am working with a QTreeWidget.

I have a structure like this:

A -> A1, A2, A3
B -> B1, B2, B3
C -> C1, C2, C3

Where A, B and C are top-level nodes and the others are their respective children.
I need to, after selecting any top-level node A, B or C, to select all their respective children
For example:

If I select A ( with the mouse ), then I need A1, A2 and A3 to be selected too.
Looking at the documentation I saw the method QTreeWidgetItem::takeChildren(), but this will also remove the children. In my case I need them not to be removed, only selected.

Any help please?

Regards

Added after 18 minutes:

I need this behavior in my QTableWidget::startDrag method.
When I select a top-level node, I need to drag and drop all its children

d_stranz
20th January 2022, 16:20
// Pseudocode

QTreeWidgetItem * A = myTree->currentItem();

auto nChildren = A->childCount();
for ( auto nChild = 0; nChild < nChildren; ++nChild )
{
QTreeWidgetItem * pChild = A->child( nChild );
if ( pChild != nullptr )
pChild->setSelected( true );
}



I need this behavior in my QTableWidget::startDrag method.
When I select a top-level node, I need to drag and drop all its children

If you are moving items (especially from one tree widget to another) you will probably have to "take" the items at some point because a tree widget item cannot belong to two trees at the same time, nor can it live in two places in the same tree.

franco.amato
20th January 2022, 16:55
Thank you,
it's possible to add those new selected items to the list returned by selectedItems ?

Basically now I have implemented this code:


void ReportsTreeWidget::startDrag(Qt::DropActions supportedActions)
{
Q_UNUSED(supportedActions)

if (selectedItems().empty())
{
return;
}

// ... more code ...

// I iterate over the selected items
for (QTreeWidgetItem *item : selectedItems())
{
// If top-level item then drag its children, not the item itself
if (!item->parent())
{
auto children = item->childCount();
for (auto child = 0; child < children; ++child)
{
QTreeWidgetItem *pChild = item->child(child);
if (pChild != nullptr)
{
pChild->setSelected(true);
}
}

item->setSelected(false);
}

// ... more code ...

QMimeData *mimeData = new QMimeData;
mimeData->setText(data);

Drag drag(this);
drag.setMimeData(mimeData);
drag.setPixmap(dragPixmap);
drag.exec(Qt::CopyAction);
}

I compose "data" from the selected items that I get with the method selectedItems() in the for loop.
I would add the new selected items (in the inner if) so that I can add them to the list. The items are not moved, but copied.
Franco

franco.amato
21st January 2022, 01:34
I solved the task by adding the new created item text to the data string.