QTreeWidget区分鼠标左右键点击事件的方法

这几天做一个项目,QTreewidget上的item需要根据的鼠标左右键点击事件来响应不同的事件,在网上搜集资料,没发现可以解决这个问题的办法,最后同事的给了我一个提示,经过自己研究qt关于QTreewidget的关于事件响应的源码,最终解决了这个问题,解决方法如下:

1.继承QTreewidget重新实现他的mouseReleaseEvent方法,为什么是release方法,因为源码里面mousePressEvent方法用来绘制treeWidget,而release方法则会发送出点击事件的信号

#ifndefTREEWIDGET_H

#define TREEWIDGET_H
#ifndef TREEWIDGET_H
#define TREEWIDGET_H
#include 
#include 
#include 


class QTreeWidget2 : public QTreeWidget
{
    Q_OBJECT
public:
    explicit QTreeWidget2( QWidget *parent = 0 );
protected:
    void mouseReleaseEvent (QMouseEvent *event);
};

#endif // TREEWIDGET_H

2.实现

#include "treeWidget.h"

QTreeWidget2::QTreeWidget2( QWidget *parent)
    :QTreeWidget(parent)
{

}

void QTreeWidget2::mouseReleaseEvent (QMouseEvent *event)
{
    if (event->button () & Qt::RightButton )
    {
        emit customContextMenuRequested( event->pos ());
    }else if (event->button () & Qt::LeftButton){
        emit itemClicked(itemFromIndex (indexAt ( event->pos () )),indexAt ( event->pos () ).column ());
    }
}

3.测试

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include 
#include  
class QTreeWidget2;
static const int itemtype1 = QTreeWidgetItem::Type;
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow( QWidget *parent = 0 );
public slots:
    void setTest2(const QPoint &pos);
    void setTest(QTreeWidgetItem*item,int column);
private:
    QTreeWidget2 *treeWidget;
    QTreeWidgetItem *currentItem;
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "treeWidget.h"
#include 
#include 

MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent)
{
    treeWidget = new QTreeWidget2;
    treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    treeWidget->setHeaderLabel ( tr("资源列表") );
    QTreeWidgetItem *root = new QTreeWidgetItem( treeWidget );
    root->setText (0,tr("root"));
    QTreeWidgetItem *item = new QTreeWidgetItem( root );
    item->setText (0,tr("a"));
    QTreeWidgetItem *item1 = new QTreeWidgetItem( item );
    item1->setText (0,tr("b"));
    QTreeWidgetItem *item2 = new QTreeWidgetItem( item1 );
    item2->setText (0,tr("c"));
    connect( treeWidget,SIGNAL(customContextMenuRequested( const QPoint &)),
             this,SLOT(setTest2(const QPoint &)));
    connect( treeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)),
             this,SLOT(setTest(QTreeWidgetItem*,int)));
    setCentralWidget ( treeWidget );
    resize ( 500,400 );
}

void MainWindow::setTest2(const QPoint &pos)
{
    currentItem = treeWidget->itemAt(pos);
    if ( currentItem == NULL )
        return;
  QMessageBox::warning (this,tr("test"),tr("hello"));
}
void MainWindow::setTest(QTreeWidgetItem*item,int column)
{
  QMessageBox::warning (this,tr("asd"),tr("sd"));
}

4.效果图

QTreeWidget区分鼠标左右键点击事件的方法_第1张图片

图1 鼠标右击
QTreeWidget区分鼠标左右键点击事件的方法_第2张图片

图2 鼠标左击



你可能感兴趣的:(Qt)