2010-01-27 102 views
6

我有一个QTableView中,我展示一个自定义模式。我想赶上鼠标右键点击,这样我可以在基础表数据打开上下文下拉菜单:的Qt4:QTableView中鼠标按钮事件没有抓到

MainWindow::MainWindow() 
{ 
    QTableView * itsView = new QTableView; 
    itsView->installEventFilter(this); 
    ... //Add other widgets and display them all 
} 

bool MainWindow::eventFilter(QObject * watched, QEvent * event) 
{ 
    if(event->type() == QEvent::MouseButtonPress) 
    printf("MouseButtonPress event!\n"); 
    else if(event->type() == QEvent::KeyPress) 
    printf("KeyPress event!\n"); 
} 

奇怪的是,我得到的所有的按键事件的正确:当我有一个单元格,然后按压一个关键,我得到了“KeyPress事件!”的消息。不过,我只当我点击周围的整个表非常薄的边框获得了“MouseButtonPress活动!”的消息。

回答

10

这是因为Tableview是这个薄边框...如果你想访问小部件的内容,你应该在Tableview的视口上安装eventFilter!

因此,我提议:

QTableView * itsView = new QTableView; 
itsView->viewport()->installEventFilter(this); 

试试这个,它应该解决您的问题!

希望它能帮助!

+1

六年多后,这个答案为我节省了一堆时间和烦恼。谢谢! – GuyGizmo 2016-10-13 17:59:23

+1

@GuyGizmo我很高兴听到:)谢谢你停下来;) – 2016-10-17 05:05:04

2

如果你需要显示上下文菜单,你可以使用tableviewcustomContextMenuRequested信号;你需要上下文菜单策略设置为Qt::CustomContextMenu该信号被触发。这样的事情:

... 
itsView->setContextMenuPolicy(Qt::CustomContextMenu); 
QObject::connect(itsView, SIGNAL(customContextMenuRequested(const QPoint &)), 
       this, SLOT(tableContextPopup(const QPoint &))); 
... 

void MainWindow::tableContextPopup(const QPoint & pos) 
{ 
    qDebug() << "show popup " << pos; 
} 

希望这会有所帮助,问候。

相关问题