给Qt的控件添加新信号

Qt的控件有时候并不提供我们想要的信号

已QLineEdit为例,它并没有提供鼠标点击的信号,此时就需要我们自己添加

方法如下:

mylineedit.h

#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H

#include <QLineEdit>
#include <QMouseEvent>

class MyLineEdit : public QLineEdit
{
    Q_OBJECT
public:
    explicit MyLineEdit(QWidget *parent = 0);
    
protected:
    virtual void mousePressEvent(QMouseEvent *event);

signals:
    void LineEditClicked();
    
public slots:
    
};

#endif // MYLINEEDIT_H

mylineedit.cpp

#include "mylineedit.h"

MyLineEdit::MyLineEdit(QWidget *parent) :
    QLineEdit(parent)
{
}

void MyLineEdit::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
       emit LineEditClicked();
    }
    QLineEdit::mousePressEvent(event);
}

这时MyLineEdit就是一个已经有了鼠标点击信号的QLineEdit,我们只需要向其他信号一样使用它就可以了


你可能感兴趣的:(C++,鼠标,qt)