QTableWidget右键菜单

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QAction *action;
    QMenu *menu;

    void actions();

public slots:
    void contextMenuEvent(QContextMenuEvent *event); //右键默认槽
    void actionClick();
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qDebug>
#include <QContextMenuEvent>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->tableWidget->setColumnCount(2);
    ui->tableWidget->setRowCount(2);

    //鼠标右键动作
    action = new QAction(this);
    actions();
    connect(action, SIGNAL(triggered(bool)), this, SLOT(actionClick())); //右键动作槽
}

//右键被按下
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
    qDebug() << "contextMenuEvent here";

    QPoint point = event->pos(); //得到窗口坐标
    QTableWidgetItem *item = ui->tableWidget->itemAt(point);
    if(item != NULL)
    {
        qDebug() << "row" << item->row(); //当前行

        menu->clear(); //清除原有菜单
        menu->addAction(action);
        menu->addSeparator();

        //菜单出现的位置为当前鼠标的位置
        menu->exec(QCursor::pos());
        event->accept();
    }
}

//添加动作
void MainWindow::actions()
{
    menu = new QMenu(); //创建菜单项
    action->setText(QString("action"));
}

//右键动作被按下
void MainWindow::actionClick()
{
    qDebug() << "actionClick here";
}

MainWindow::~MainWindow()
{
    delete ui;
}

1

posted @ 2018-08-22 15:13  thomas_blog  阅读(1332)  评论(2编辑  收藏  举报