7

I am working on QTreeView to explore the hard drive partition.In my Qtreeview, on Double click event on its items of treeview single click event also generates.

connect(ui->treeview,SIGNAL(doubleclicked(QModelIndex)),this,SLOT(Ondoubleclicktree(QModelIndex)));
connect(ui->treeview,SIGNAL(clicked(QModelIndex)),this,SLOT(Onclickedtree(QModelIndex)));

I want only double click event. Please help me how to stop it for entering in single click event slot. Thanks.

Ashish
  • 219
  • 2
  • 6
  • 22
  • 2
    Do you really need to handle both events: click and double click? If not, remove one of the connections. – vahancho Nov 13 '13 at 08:25
  • i need both of the connections – Ashish Nov 13 '13 at 12:10
  • Here is the similar question: http://stackoverflow.com/questions/4627347/distinguish-between-single-and-double-click-events-in-qt – vahancho Nov 13 '13 at 12:31
  • Thanks for your response, its a little bit typical. Can you please elaborate that solution given by wysota or any other way for doing this. – Ashish Nov 13 '13 at 12:38
  • I suppose that it is pretty descriptive itself. You need to set up a timer and start it as soon as you get the click event. After timer is expired (several milliseconds later) you can check wither a double click event was also received and process either of them of both (depends on your goal). – vahancho Nov 13 '13 at 12:46

1 Answers1

3

Trying to put things that were already mentioned together: if you are not worried about a slight lag in reaction to a single click, you only need to set up a QTimer in your class which you start on single click and stop if you receive a second click within a certain time window. You then just connect the timeout of the timer to the slot that does what you want to do on a single click.

One way of setting this up (certainly not the only way and probably not the most elegant) you see below:

mytreeview.h

#ifndef MYTREEVIEW_H
#define MYTREEVIEW_H

#include <QTreeView>
#include <QTimer>

class MyTreeView: public QTreeView
{
  Q_OBJECT
  public:
  MyTreeView(QWidget *parent = 0);

protected:
  virtual void mouseDoubleClickEvent(QMouseEvent * event);
  virtual void mousePressEvent(QMouseEvent * event);

private:
  QTimer timer;

private slots:
  void onSingleClick();

};

mytreeview.cpp

#include "mytreeview.h"

#include <QtCore>


MyTreeView::MyTreeView(QWidget *parent) : QTreeView(parent)
{
  connect(&timer,SIGNAL(timeout()),this,SLOT(onSingleClick()));
}


void MyTreeView::mouseDoubleClickEvent(QMouseEvent * event)
{
  Q_UNUSED(event);
  qDebug() << "This happens on double click";
  timer.stop();
}


void MyTreeView::mousePressEvent(QMouseEvent * event)
{
  Q_UNUSED(event);
  timer.start(250);
}

void MyTreeView::onSingleClick()
{
  qDebug() << "This happens on single click";
  timer.stop();
}

Let me know if this helps.

Erik
  • 2,137
  • 3
  • 25
  • 42