QT的很多控件没有设置鼠标点击事件,这里以lineEdit为例重写类并添加鼠标点击事件
具体步骤如下:
1. 重写lineEdit类,自定义mousePressEvent的相关操作,在头文件中申明SIGNAL
2. 在主程序中添加lineEdit的槽函数
3. 在UI窗口中将lineEdit控件提升为自定义的lineEdit类
具体源码如下:
mylineedit.h
1. #ifndef MYLINEEDIT_H 2. #define MYLINEEDIT_H 3. 4. #include <QWidget> 5. #include <QLineEdit> 6. #include <QMouseEvent> 7. 8. class myLineEdit : public QLineEdit 9. { 10. Q_OBJECT 11. public: 12. explicit myLineEdit(QWidget *parent = nullptr); 13. 14. void mousePressEvent(QMouseEvent *e); 15. 16. signals: 17. void clicked(); 18. 19. }; 20. 21. #endif // MYLINEEDIT_H
mylineedit.cpp
1. #include "mylineedit.h" 2. 3. myLineEdit::myLineEdit(QWidget *parent) : QLineEdit(parent) 4. { 5. 6. } 7. 8. void myLineEdit::mousePressEvent(QMouseEvent *e) 9. { 10. if(e->button() == Qt::LeftButton) //鼠标左键点击触发signal 11. { 12. emit clicked(); 13. } 14. 15. }
mainwindow.h
1. #ifndef MAINWINDOW_H 2. #define MAINWINDOW_H 3. 4. #include <QMainWindow> 5. 6. QT_BEGIN_NAMESPACE 7. namespace Ui { class MainWindow; } 8. QT_END_NAMESPACE 9. 10. class MainWindow : public QMainWindow 11. { 12. Q_OBJECT 13. 14. public: 15. MainWindow(QWidget *parent = nullptr); 16. ~MainWindow(); 17. 18. private: 19. Ui::MainWindow *ui; 20. 21. private slots: 22. void lineEditClicked(); 23. 24. 25. }; 26. #endif // MAINWINDOW_H
mainwindow.cpp
1. #include "mainwindow.h" 2. #include "ui_mainwindow.h" 3. 4. #include "mylineedit.h" 5. 6. MainWindow::MainWindow(QWidget *parent) 7. : QMainWindow(parent) 8. , ui(new Ui::MainWindow) 9. { 10. ui->setupUi(this); 11. 12. ui->lineEdit->setText("1"); 13. 14. connect(ui->lineEdit, SIGNAL(clicked()), this, SLOT(lineEditClicked())); 15. } 16. 17. void MainWindow::lineEditClicked() 18. { 19. int t = ui->lineEdit->text().toInt(); 20. if(t == 1) 21. { 22. ui->lineEdit->setText("0"); 23. ui->lineEdit->setStyleSheet("background-color:gray"); 24. } 25. if(t == 0) 26. { 27. ui->lineEdit->setText("1"); 28. ui->lineEdit->setStyleSheet("background-color:red"); 29. } 30. } 31. 32. MainWindow::~MainWindow() 33. { 34. delete ui; 35. } 36.
lineEdit控件的提升操作,点击进入窗口ui设计界面——选中lineEdit控件——右键——提升为——在提升类名称里添加刚刚重写的类myLineEdit,然后选中——提升;
完成提升操作之后,可以看到lineEdit控件已经变成myLineEdit属性