#include #include #include #include #include namespace { using std::views::iota; constexpr int arbitraryNumberOfChildren = 3; constexpr auto numberOfBytesInAPointer = sizeof(std::uintptr_t); constexpr auto numberOfNibblesInAByte = 2; constexpr auto numberOfCharactersProceedingAHexadecimalNumber = 2; constexpr auto numberOfFormatCharactersForPointer = numberOfBytesInAPointer * numberOfNibblesInAByte + numberOfCharactersProceedingAHexadecimalNumber; static void PrintChildren_(auto& item) { std::cout << std::format(" {}'s children", item->text().toStdString()) << std::endl; for (int i : iota(0, arbitraryNumberOfChildren)) { std::cout << std::format(" {:#0{}x}", reinterpret_cast(item->child(i)), numberOfFormatCharactersForPointer) << std::endl; } }; static void AddChildrenToItem_(auto& item) { for ([[maybe_unused]] int i : iota(0, arbitraryNumberOfChildren)) { item->appendRow(new QStandardItem()); } }; } int main() { std::cout << "Code in question: secondParent's children are null" << std::endl; { auto firstParent = std::make_unique("firstParent"); auto secondParent = std::make_unique("secondParent"); AddChildrenToItem_(firstParent); PrintChildren_(firstParent); std::cout << "Swapping children" << std::endl; for (int i : iota(0, arbitraryNumberOfChildren)) { secondParent->setChild(i, firstParent->takeChild(i)); } PrintChildren_(secondParent); } std::cout << std::endl; std::cout << "Workaround 1: Ensure the firstParent has a model before taking its children" << std::endl; { auto model = std::make_unique(); auto firstParent = model->invisibleRootItem(); firstParent->setText("firstParent"); auto secondParent = std::make_unique("secondParent"); AddChildrenToItem_(firstParent); PrintChildren_(firstParent); std::cout << "Swapping children" << std::endl; for (int i : iota(0, arbitraryNumberOfChildren)) { secondParent->setChild(i, firstParent->takeChild(i)); } PrintChildren_(secondParent); } std::cout << std::endl; std::cout << "Workaround 2: Use takeColumn" << std::endl; { auto firstParent = std::make_unique("firstParent"); auto secondParent = std::make_unique("secondParent"); AddChildrenToItem_(firstParent); PrintChildren_(firstParent); std::cout << "Swapping children" << std::endl; secondParent->insertColumn(0, firstParent->takeColumn(0)); PrintChildren_(secondParent); } std::cout << std::endl; }