效果
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include"QStandardItemModel"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void _on_m_treeView_current_changed(const QModelIndex& current, const QModelIndex& previous);
void _on_m_treeView_MenuPopup(const QPoint &pos);
};
#endif
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QStandardItemModel* m_standardItemModel = new QStandardItemModel();
m_standardItemModel->setHorizontalHeaderLabels(QStringList(QStringLiteral("资源")));
QStandardItem* itemRoot = m_standardItemModel->invisibleRootItem();
QStandardItem* itemCam = new QStandardItem(QStringLiteral("相机"));
itemRoot->appendRow(itemCam);
QList<QStandardItem*> camList;
camList.append(new QStandardItem("cam1"));
camList.append(new QStandardItem("cam2"));
camList.append(new QStandardItem("cam3"));
itemCam->appendRows(camList);
QStandardItem* itemImg = new QStandardItem(QStringLiteral("图片"));
itemRoot->appendRow(itemImg);
QList<QStandardItem*> imgList;
imgList.append(new QStandardItem("img1"));
imgList.append(new QStandardItem("img2"));
imgList.append(new QStandardItem("img3"));
itemImg->appendRows(imgList);
ui->m_treeView->setModel(m_standardItemModel);
ui->m_treeView->expandAll();
connect(ui->m_treeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &MainWindow::_on_m_treeView_current_changed);
connect(ui->m_treeView, &QTreeView::customContextMenuRequested, this, &MainWindow::_on_m_treeView_MenuPopup);
itemCam->setCheckable(true);
itemImg->setCheckable(true);
itemCam->setIcon(QIcon("C:/Users/admin/Desktop/Alexnet_Structure.png"));
ui->m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->m_treeView->setContextMenuPolicy(Qt::CustomContextMenu);
}
void MainWindow::_on_m_treeView_current_changed(const QModelIndex& current, const QModelIndex& previous)
{
QModelIndex index = current.sibling(current.row(), 0);
}
void MainWindow::_on_m_treeView_MenuPopup(const QPoint& pos)
{
QMenu* menu = new QMenu(ui->m_treeView);
menu->addAction(QStringLiteral("添加"));
menu->addAction(QStringLiteral("删除"));
menu->exec(ui->m_treeView->mapToGlobal(pos));
}
MainWindow::~MainWindow()
{
delete ui;
}