QLineEdit控件焦点选中所有文本,键盘enter键发送当前文本信号及输入限制

1.焦点选中框内文本

1.1新建一个类,继承QLineEdit:重写鼠标点击事件

protected:
    virtual void mousePressEvent(QMouseEvent *event);
void LineEdit::mousePressEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    setFocus();
    selectAll();
}

1.2将控件QLineEdit提升为LineEdit即可

2.修改好QLineEdit文本后按下键盘enter键发送当前文本

2.1新建了一个继承带有ui的QWidget类:ui界面有个QLineEdit并提升为LineEdit

.h

#ifndef MYKEYLINEEDIT_H
#define MYKEYLINEEDIT_H

#include 

namespace Ui {
class MyKeyLineEdit;
}

class MyKeyLineEdit : public QWidget
{
    Q_OBJECT

public:
    explicit MyKeyLineEdit(QWidget *parent = nullptr);
    ~MyKeyLineEdit();

private:
    Ui::MyKeyLineEdit *ui;
    int m_nState = 0;   //0-int 1-float

protected:
    void keyPressEvent(QKeyEvent *event);
signals:
    void sig_SendEditDataInt(int);
    void sig_SendEditDataFloat(float);

public slots:
    void SetState(int state);
    void setEnable(bool state);
};

#endif // MYKEYLINEEDIT_H

.cpp

#include "mykeylineedit.h"
#include "ui_mykeylineedit.h"
#include 

MyKeyLineEdit::MyKeyLineEdit(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyKeyLineEdit)
{
    ui->setupUi(this);

    ui->lineEdit->setInputMethodHints(Qt::ImhDigitsOnly);
}

MyKeyLineEdit::~MyKeyLineEdit()
{
    delete ui;
}

void MyKeyLineEdit::keyPressEvent(QKeyEvent *event)
{
    if( event->key() == Qt::Key_Return )
    {
        if( 0 == m_nState )
        {
            int nData = ui->lineEdit->text().toInt();
            emit sig_SendEditDataInt(nData);
        }
        else if( 1 == m_nState )
        {
            float fData = ui->lineEdit->text().toFloat();
            emit sig_SendEditDataFloat(fData);
        }
    }
}

void MyKeyLineEdit::SetState(int state)
{
    m_nState = state;
}

void MyKeyLineEdit::setEnable(bool state)
{
    ui->lineEdit->setEnabled(state);
}

3.输入限制

QLineEdit的整数和浮点数输入限制需要自己重写一下才行,不然直接用QLineEdit自带的好像会设置不成功。

你可能感兴趣的:(QT,qt,ui,开发语言)