重载了QTabWidget(由于tabBar()是protected),这样就可以获取到标签了。
1 class Tab : public QTabWidget 2 { 3 Q_OBJECT 4 public: 5 Tab(QWidget *parent = 0); 6 QTabBar* GetBar(); 7 protected: 8 void mousePressEvent(QMouseEvent *event); 9 };
然后在实现一个事件过滤器,首先判断事件是双击事件,然后判断是否为标签位置,如果是则删除当前标签页,由于双击事件中必触发单击,即标签页选中事件,因此无需考虑双击其他标签页引起的index变更问题。
1 #ifndef MYEVENTFILTER_H 2 #define MYEVENTFILTER_H 3 #include <QMainWindow> 4 #include <QMouseEvent> 5 #include "tab.h" 6 7 extern int tabindex_current; 8 extern int tabindex_old; 9 extern Tab *tabWidget; 10 extern QPoint tableft; 11 extern int tabwidth; 12 extern int tabheight; 13 14 //实现双击关闭Tab标签 15 class myEventFilter: public QObject 16 { 17 public: 18 myEventFilter():QObject() 19 {}; 20 ~myEventFilter(){}; 21 22 bool eventFilter(QObject* object,QEvent* event) 23 { 24 if (event->type()==QEvent::MouseButtonDblClick) 25 { 26 QMouseEvent *e = static_cast<QMouseEvent*>(event); 27 QPoint pos = e->pos(); 28 int x1 = tableft.x(); 29 int x2 = tableft.x()+tabwidth; 30 int y1 = tableft.y(); 31 int y2 = tableft.y()+tabheight; 32 if (pos.x() >= x1 && pos.y() >= y1 && pos.x() <= x2 && pos.y() <= y2) 33 tabWidget->removeTab(tabindex_current); 34 } 35 return QObject::eventFilter(object,event); 36 }; 37 }; 38 39 #endif // MYEVENTFILTER_H
最后绑定到主函数main中,这样就可捕捉到所有的事件了:
1 qApp->installEventFilter(new myEventFilter());
另外,需在标签页切换时更新宽度信息(高度无需更新):
1 void MainWindow::updateBar() 2 { 3 tabindex_current = tabWidget->currentIndex(); 4 tabindex_old = tabindex_current; 5 QTabBar *bar = tabWidget->GetBar(); 6 if (bar->size().width() > 0) 7 tabwidth = bar->size().width(); 8 }
时间: 2024-10-19 10:24:19