Reputation: 26004
Is there a way that I can override the Events of those widgets that I have placed on my designer?
I have seen tutorials demonstrating how to use Events in Qt but they all force the coder to create the widgets from scratch (by inheriting them from the widget they want the event to be associated and then add that widgets programmatically to the form) and when someone is using the QtCreator designer those examples are of no use.
How can I override a specific event for a specific widgets on my form in Qt?
Upvotes: 2
Views: 1306
Reputation: 26004
Here is how I did it. First I needed to add eventFilter(QObject*,QEvent*);
to the header of my Mainwindow (my form) and then inside its cpp file, defined that method.
And finally install the filter in constructor. The code below represents my forms content (MainWindow.h and MainWindo.cpp).
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
bool eventFilter( QObject* sender, QEvent* event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QMessageBox"
#include <QKeyEvent> //dont forget to add this
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->lineEdit->installEventFilter(this); //installing the eventfilter for lineEdit
}
bool MainWindow::eventFilter(QObject *sender, QEvent *event)
{
if (sender == ui->lineEdit)
{
if(event->type()== QEvent::KeyPress)
{
QKeyEvent * keyEvent = (QKeyEvent*)(event);
if( keyEvent->key() == Qt::Key_Control)
{
QMessageBox::information(this,"Salam ","Control Key was ressed");
return true;
}else
{
return false;
}
}
}
return QWidget::eventFilter(sender,event);
}
MainWindow::~MainWindow()
{
delete ui;
}
Upvotes: 0