QTreeWigetItem - 如何管理单击以直接更改项目文本的名称

时间:2014-12-11 19:31:19

标签: c++ qt qtreeview qtreewidgetitem

我创建了一个QTreeView,它由QTreeWidgetItem提交。我的应用程序是一种文件浏览器。

ViewTree的定义如下:

void MainWindow::createTreeView()
{
    TreeViewSection = new QWidget();

    QVBoxLayout *TreeViewLayout = new QVBoxLayout(TreeViewSection);

    MyTree = new TreeWidget();
    contextMenu = new QMenu(MyTree);
    MyTree->setContextMenuPolicy(Qt::ActionsContextMenu);

    addFolderAction = new QAction("Add Folder", contextMenu);
    MyTree->addAction(addFolderAction);
    connect(addFolderAction, SIGNAL(triggered()),this,SLOT(onAddFolderAction()));

    deleteAction = new QAction("Delete", contextMenu);
    MyTree->addAction(deleteAction);
    connect(deleteAction, SIGNAL(triggered()),this,SLOT(onDeleteAction()));

    MyTree->setSortingEnabled(true);
    MyTree->setColumnWidth(0, 400);

    headerItem = new QTreeWidgetItem();

    headerItem->setText(0,QString("File Name"));
    headerItem->setText(1,QString("Last Modified"));
    headerItem->setText(2,QString("Size"));
    MyTree->setHeaderItem(headerItem);

    MyTree->setAcceptDrops(true);
    MyTree->setDragEnabled(true);
    MyTree->setDragDropMode(QAbstractItemView::InternalMove);
    MyTree->setDefaultDropAction(Qt::MoveAction);
    MyTree->setDropIndicatorShown(true);
    MyTree->setDragDropOverwriteMode(true);
    MyTree->setSelectionMode(QAbstractItemView::SingleSelection);

    TreeViewLayout->addWidget(MyTree);

}

我添加了一个“添加文件夹”按钮,如下面定义的操作:

void MainWindow::onAddFolderAction()
{
    QList<QTreeWidgetItem *> item;
    uint32_t index;

    item = MyTree->selectedItems();
    if (item.empty())
        index = 0;
    else {
        QString str = item[0]->text(0);
        QByteArray latin_str = str.toLatin1();
        char *utf8_text = latin_str.data();

        index = m_device.getIdByName(utf8_text);
    }
    if(m_device.isFolder(index) == true) {
        QTreeWidgetItem* child = new QTreeWidgetItem();
        child->setText(0, "NewFolder");
        child->setText(1, "--");
        child->setText(2, "--");

        item[0]->addChild(child);
        item[0]->setExpanded(true);
      //item[0]->setSelected();

// MyTree-&gt; edit(selectedItem());

        m_device.CreateNewFolder("New Folder", index);
    } 
}

如您所见,默认情况下我在mtp FS系统上创建一个“NewFolder”。

在创建文件夹之前我想要做什么,我希望能够将“NewFolder”重命名为用户想要的内容。我不想创建弹出窗口来输入文本。我想要的是一种“重命名”行为。该文件夹显示在树视图中,选择了新文件夹并允许直接更改文本。就像在Finder上单击文件夹名称一样,它会被选中,用户可以在查找器中更改名称而不需要任何弹出窗口

由于

1 个答案:

答案 0 :(得分:1)

如果您想在创建项目后立即编辑该项目,您应该可以通过simply calling the editor来实现此行为:

QTreeWidgetItem* child = new QTreeWidgetItem();
child->setText(0, "NewFolder");
child->setText(1, "--");
child->setText(2, "--");
child->setFlags(child->flags() | Qt::ItemIsEditable);

item[0]->addChild(child);
item[0]->setExpanded(true);

MyTree->editItem(child);