如何创建从一个QTreeWidget删除项目并将其添加到另一个项目的函数?

时间:2019-05-14 23:52:06

标签: c++ qt

我编写了应该在两个QTreeWidgets(treeAvailable和treeSelected)之间移动项目的代码。树是单列,包含QStrings。我以为下面的代码可以工作,但是我似乎无法弄清楚为什么不行。

DataPlaneEditor::DataPlaneEditor(QWidget* parent) :
    QDialog(parent),
    ui(new Ui::DataPlaneEditor)
{
    ui->setupUi(this);
    connect(ui->pushAdd, &QPushButton::clicked, this, &DataPlaneEditor::addButton);
    connect(ui->pushRemove, &QPushButton::clicked, this, &DataPlaneEditor::removeButton);
    connect(ui->treeAvailable, &QTreeWidget::doubleClicked, this, &DataPlaneEditor::addButton);
    connect(ui->treeSelected, &QTreeWidget::doubleClicked, this, &DataPlaneEditor::removeButton);
}

void DataPlaneEditor::addButton()
{
    QTreeWidgetItem* chosenData = ui->treeAvailable->currentItem();
    if (!chosenData) return;
    ui->treeAvailable->insertTopLevelItem(0, chosenData);
    ui->treeSelected->removeItemWidget(chosenData, 0);
}

void DataPlaneEditor::removeButton()
{
    QTreeWidgetItem* chosenData = ui->treeSelected->currentItem();
    if (!chosenData) return;
    ui->treeAvailable->insertTopLevelItem(0, chosenData);
    ui->treeSelected->removeItemWidget(chosenData, 0);
}

1 个答案:

答案 0 :(得分:2)

QTreeWidget::removeItemWidget删除与QTreeWidgetItem关联的窗口小部件,而不是项目本身。要删除项目本身,请查看QTreeWidget::takeTopLevelItemQTreeWidgetItem::takeChild