zoukankan      html  css  js  c++  java
  • Qt TableView右键弹出菜单

    TableView右键弹出菜单

    关于TableView的控件使用,这里不做解释了,直接说诉求,右键点击选中的某一行(术语称item),弹出菜单。操作结果如下图:
    在这里插入图片描述
    实现过程主要包括以下几个重点:

    1、初始化一个TableView控件表

    主要需要完成表头的设置,表格属性的设置。
    代码如下:

    point_time_model 表示TableView控件对应的model:

    point_time_model = new QStandardItemModel(ui->Point_Time_tableView);

    初始化:

     1 const int table_cols = 3; //有几列
     2 QStringList headerList;
     3 headerList <<  "位置"  <<  "监测时长"  <<  "     " ;
     4 point_time_model->setHorizontalHeaderLabels(headerList);
     5 point_time_model->setColumnCount(table_cols);
     6 //设置列表属性
     7 ui->Point_Time_tableView->verticalHeader()->setVisible(false);   //隐藏列表头
     8 ui->Point_Time_tableView->setSelectionBehavior(QAbstractItemView::SelectRows); //选择整行
     9 ui->Point_Time_tableView->setSelectionMode(QAbstractItemView::SingleSelection); //只选择一行
    10 ui->Point_Time_tableView->horizontalHeader()->setStretchLastSection(true); //最后一列填满表
    11 ui->Point_Time_tableView->setContextMenuPolicy(Qt::CustomContextMenu); //可弹出右键菜单

    其中,ui->Point_Time_tableView->setContextMenuPolicy(Qt::CustomContextMenu); !!!这里是重点!!!

    2 、为TableView控件表添加右键菜单

    首先需要创建一个菜单,并为菜单添加行为,代码如下:
    .cpp文件中

    1 QMenu *popMenu; //菜单
    2 popMenu = new QMenu(ui->Point_Time_tableView);
    3 QAction *actionUpdateInfo = new QAction();
    4 QAction *actionDelInfo = new QAction();
    5 actionUpdateInfo ->setText(QString("修改"));
    6 actionDelInfo ->setText(QString("删除"));
    7 popMenu->addAction(actionUpdateInfo);
    8 popMenu->addAction(actionDelInfo);

    到这里,右键菜单已经建立好了,接下来的关键步骤是,如何右键点击一行,弹出该菜单,需要用到槽和信号机制。

    3 、右键弹出菜单的槽和信号机制

    .h文件中

    1 private slots:
    2      //右键菜单响应函数
    3      void slotContextMenu(QPoint pos);

    .cpp文件中,在第2步的代码之后初始化槽信号的connect函数:

    connect(ui->Point_Time_tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotContextMenu(QPoint)));

    (1)该连接函数中的SIGNAL(customContextMenuRequested(QPoint))是QMenu的自带响应信号。
    (2)SLOT(slotContextMenu(QPoint)))中的槽函数需要自己实现,代码如下:

    1 void MainWindow::slotContextMenu(QPoint pos)
    2 {
    3    auto index = ui->Point_Time_tableView->indexAt(pos);
    4     if (index.isValid())
    5     {
    6         popMenu->exec(QCursor::pos()); // 菜单出现的位置为当前鼠标的位置
    7     }
    8 }

    以上,右键点击某一行时,菜单就会出现,相应的每一个菜单需要什么样的响应操作,就是后续的槽和信号之间的操作。

  • 相关阅读:
    Generate Parentheses
    Length of Last Word
    Maximum Subarray
    Count and Say
    二分搜索算法
    Search Insert Position
    Implement strStr()
    Remove Element
    Remove Duplicates from Sorted Array
    Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/13632865.html
Copyright © 2011-2022 走看看