首先看头文件:
//mainwindows.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
void initTableWidget(QString title,QStringList Headers);
void ctxMenu(const QPoint &pos);
private:
Ui::MainWindow *ui;
TableWidget *m_Table;
};
下面看源文件:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
QStringList Headers;
Headers << "name" << "FileID";
initTableWidget("Catalog Detail",Headers);
this->setCentralWidget(m_Table);
for(int i = 0;i < 10;i++){
this->m_Table->insertRowAtLast();
for(int j = 0;j < 5;j++){
this->m_Table->insertItemWithContent(j,"TestTable");
}//end of for(j)
}//end of for(i)
m_Table->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_Table, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));
}//end of method QMainWindow
void MainWindow::initTableWidget(QString title,QStringList Headers){
m_Table = new TableWidget();
m_Table->initTableWidget(Headers);
//setTableWidgetStype(m_CatalogTable);
}//end of method initTableWidget
QMenu *cmenu = NULL;
void MainWindow::ctxMenu(const QPoint &pos) {
if(cmenu){//保证同时只存在一个menu,及时释放内存
delete cmenu;
cmenu = NULL;
}//end of if
QMenu *cmenu = new QMenu(m_Table);
cmenu->addAction(tr("Test Item"), this, SLOT(test_slot()));
QAction *ascendSortAction = cmenu->addAction("Test1");
QAction *descendSortAction = cmenu->addAction("Test2");
QAction *filterAction = cmenu->addAction("Test3");
QAction *reshowAction = cmenu->addAction("Test4");
connect(ascendSortAction, SIGNAL(triggered(bool)), this, SLOT(sort_ascend()));
connect(descendSortAction, SIGNAL(triggered(bool)), this, SLOT(sort_descend()));
connect(filterAction, SIGNAL(triggered(bool)), this, SLOT(show_filter_dlg()));
connect(reshowAction, SIGNAL(triggered(bool)), this, SLOT(reshow_data()));
//cmenu->exec(m_Table->mapToGlobal(pos));
cmenu->exec(QCursor::pos());
}//end of method ctxMenu
看完以上代码,大家知道,我的需求就是在TableWiget中弹出右键菜单cmenu,但是经过查询晚上好多帖子,他们都是这么干的,请各位热心达人帮忙一下,看看到底怎么回事右键菜单无法弹出。
测试demo在http://download.csdn.net/source/2248724
------解决方案--------------------
不知 帮顶。。。。。。
------解决方案--------------------
Qt\qt\examples\widgets\shapedclock\release
右键菜单貌似可以很简单的做出来,如这个小例子
------解决方案--------------------
这里是个是我以前整理了,可以参考下
http://blog.csdn.net/killua_hzl/archive/2010/02/04/5288782.aspx