QTreeWidget はそのまま使えるツリー構造用のコンポーネントです。そのまま、というのは QTreeView 派生クラスなど作らなくても備え付けのデータクラスが使えるという意味です。
QTreeWidget へアイテムを追加するコードはヘルプにもありますが、ここではルート要素へも追加できるコードを置いておきます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void MainWindow::addItem() { | |
bool ok; | |
QString text = QInputDialog::getText(this, tr("New Item"), tr("New Item:"), | |
QLineEdit::Normal, "", &ok); | |
if (ok && !text.isEmpty()) { | |
if (m_pItem == nullptr) { | |
QStringList lst = {text}; | |
QTreeWidgetItem *item = | |
new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr), lst); | |
ui->treeWidget->addTopLevelItem(item); | |
} else { | |
QTreeWidgetItem *newItem = new QTreeWidgetItem(m_pItem); | |
newItem->setText(0, text); | |
m_pItem->setExpanded(true); | |
} | |
} | |
} |
アイテムを削除する方法はこちらです。ルート要素の削除もできます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void MainWindow::deleteItem() { | |
QList<QTreeWidgetItem *> items = ui->treeWidget->selectedItems(); | |
QTreeWidgetItem *pp = nullptr; | |
if (!items.isEmpty()) { | |
foreach (QTreeWidgetItem *item, items) { | |
pp = item->parent(); | |
if (pp != nullptr) { | |
pp->removeChild(item); | |
} | |
delete item; | |
} | |
} | |
} |