PDA

View Full Version : mousePressEvent do not work



dexli
24th March 2011, 14:25
Hi all,

I fail to get the mousePressEvent working for QDateEdit.

If the right button is clicked a menue shows up. Is there a way to setup my one menue for this ? (add items at least)

Thanks
Dexli


// Mywidget.h

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QtGui>

class MyWidget : public QDateEdit

{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
protected:
virtual void mousePressEvent ( QMouseEvent * event ) ;
public slots:

};

#endif // MYWIDGET_H

// MyWidget.cpp

#include <QMessageBox>
#include "mywidget.h"

MyWidget::MyWidget(QWidget *parent ):
QDateEdit(parent)
{
setDate(QDate(1977,2,15));

}
void MyWidget::mousePressEvent ( QMouseEvent * event )
{
QMessageBox *box = new QMessageBox();
box->setText("Button geklickt");
box->show();
};

// Main.cpp
#include <QtGui>
#include "mywidget.h"

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
MyWidget* dateed = new MyWidget(&window);
QHBoxLayout* layout = new QHBoxLayout(&window);
layout->addWidget(dateed);
window.show();
return app.exec();
}

Rhayader
24th March 2011, 16:27
If you want to do something with the right click you should subclass the contextMenuEvent(QContextMenuEvent *event)

Mywidget.h


#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QtGui>
class QAction;

class MyWidget : public QDateEdit

{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
protected:
virtual void contextMenuEvent(QContextMenuEvent *event);
public slots:
private:
QAction *actionNew;

};

#endif // MYWIDGET_H


MyWidget.cpp


#include <QMessageBox>
#include <QAction>
#include "mywidget.h"

MyWidget::MyWidget(QWidget *parent ):
QDateEdit(parent)
{
setDate(QDate(1977,2,15));
actionNew = new QAction(tr("Do Something New"), this);
actionNew->setShortcuts(QKeySequence::New);
// connect(actionNew, SIGNAL(triggered()), this, SLOT(DoSomethingNew()));
}

void MyWidget::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menuRight(this);
menuRight.addAction(actionNew);

menuRight.exec(event->globalPos());
}


NOTE: this code replaces the default context menu

dexli
25th March 2011, 11:05
Hi Rhayader, hi rest

thanks for this hint.
In the meantime i found out why the mouseevents do not work as i expected.
Actually they work but not for the edit field (QlineEdit) they work for the QSpinBox.
If one click on the arrow the are called.


Two additional questions :
1. How to overwrite the QLineEdit mouseevent methods.
2. How can I access the 'original' menue to add the action there instead of creatin a new menu.

Thanks and have fun
Dexli