How to know if QTimeEdit field clicked?
-
I need to listen click events of line edits&time edits. Line edit works but time edit does not work:
MyClass::MyClass(QWidget *parent) : QWidget(parent), ui(new Ui::MyClass) { ui->setupUi(this); ui->lineEdit->installEventFilter(this); ui->timeEdit->installEventFilter(this); } bool MyClass::eventFilter(QObject* object, QEvent* event) { if((object == ui->lineEdit || object == ui->timeEdit) && event->type() == QEvent::MouseButtonPress) { qDebug() << "mouse clicked"; return false; } return false; }
Any idea?
If I click the arrows near the timeEdit, the event is occuring but if i click text part, it doesnt occur.
-
@masa4
AQTimeEdit
may have some other widget for the text editing field, and events for that may not filtered by theQTimeEdit
level, I don't know. Try aui->timeedit->findChildren<QWidget *>()
, if it has child widgets maybe you need to install aneventFilter()
on those or change yourif (object == ...
conditions? -
The problem is with QAbstractSpinBox, it does not take mouse press events on its QLineEdit.
So I looked it up and found this solution, basically just sub-class QTimeEdit, and use its lineEdit(it's its child), and install your event filter on it. Which is what @JonB told you to try as well.
Here's my implementation:
mainwindow.cpp
#include "mainwindow.h" #include "./ui_mainwindow.h" #include <QLayout> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); MyTimeEdit *timee = new MyTimeEdit(this); //find TimeEdit's child, just like JonB says, but specify that it's a QLineEdit editor = timee->findChild<QLineEdit *>(); editor->installEventFilter(this); this->layout()->addWidget(timee); this->timee->setGeometry(20,20,50,50); } MainWindow::~MainWindow() { delete ui; } bool MainWindow::eventFilter(QObject* object, QEvent* event) { if(object == editor && event->type() == QEvent::MouseButtonPress) { fprintf(stderr,"you have clicked\n"); return false; } return false; }
mainwindow.h
:#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QWidget> #include <QLineEdit> #include <QTimeEdit> class MyTimeEdit : public QTimeEdit { Q_OBJECT public: MyTimeEdit(QWidget *parent = nullptr){}; QLineEdit* lineEdit(){}; }; QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); MyTimeEdit *timee = new MyTimeEdit(this); QLineEdit *editor; protected: bool eventFilter(QObject* object, QEvent* event) override; private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H