contextMNU=new QMenu();contextMNU->addAction(actSomeAction);
TABLE_VIEW=new QTableView();TABLE_VIEW->setContextMenuPolicy(Qt::CustomContextMenu);connect(TABLE_VIEW, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(slotShowContextMenu(const QPoint &)));
void slotShowContextMenu(const QPoint &pos){ contextMNU->exec(TABLE_VIEW->mapToGlobal(pos));}
#ifndef TABLEWIDGET_H#define TABLEWIDGET_H//#include <QtGui>class QMenu;class QAction;class TableWidget : public QTableWidget{ Q_OBJECTpublic: TableWidget(int, int );protected: void contextMenuEvent(QContextMenuEvent *event);private slots: void add(); void remove();private: void createActions(); QAction *addAct; QAction *removeAct;};#endif
#include "tablewidget.h"//-----------------------------------------------------------------------------------------------TableWidget::TableWidget(int rows, int columns ) : QTableWidget( rows, columns) { setRowCount(rows); setColumnCount(columns); for (int i = 0; i < rows; ++i) { QTableWidgetItem *item = new QTableWidgetItem(QString("Element")+QString::number(i)); setItem( i-1 , 1, item); } createActions();}//----------------------------------------------------------------------------------------------- void TableWidget::createActions() { addAct = new QAction(tr("Add"), this); connect(addAct, SIGNAL(triggered()), this, SLOT(add())); removeAct = new QAction(tr("Remove"), this); connect(removeAct, SIGNAL(triggered()), this, SLOT(remove()));}//-----------------------------------------------------------------------------------------------void TableWidget::add() { qDebug() << "add"<< currentRow()<< currentColumn(); }//-----------------------------------------------------------------------------------------------void TableWidget::remove() { qDebug() << "remove"<< currentRow() << currentColumn(); }//-----------------------------------------------------------------------------------------------void TableWidget::contextMenuEvent(QContextMenuEvent *event) { QMenu menu(this); menu.addAction(addAct); menu.addAction(removeAct); menu.exec(event->globalPos()); }
#include "tablewidget.h"//int main(int argc, char ** argv){ QApplication app( argc, argv ); TableWidget table(3,1); table.show(); return app.exec();}
void MainWindow::contextMenuEvent( QContextMenuEvent * e ) { QAction *pRemoveAction = new QAction("Видалити",this); connect(pRemoveAction ,SIGNAL(triggered()),this,SLOT(toolButton_DeleteTrack_Clicked())); // QMenu *pContextMenu = new QMenu( this); pContextMenu->addAction(pRemoveAction ); // pContextMenu->exec( e->globalPos() ); delete pContextMenu; pContextMenu = NULL;}