c++ - inputMask 用空格填充 QLineEdit

标签 c++ qt qlineedit input-mask

当我将inputMask设置为“99999”,运行程序,鼠标点击QLineEdit时,它填充了5个空格,所以我必须先删除空格,然后才输入我需要的值。

我试过将光标位置设置为 0 ,但它不起作用。还尝试将文本设置为空字符串,结果相同。

ui->engineCapacity_lineEdit->setInputMask("99999");
ui->engineCapacity_lineEdit->setCursorPosition(0);
ui->engineCapacity_lineEdit->setText("");

它假设将光标放在 lineEdit 的开头,而不是在该行的第 5 个字符上

最佳答案

默认情况下 QLineEdit 将根据点击的位置设置光标,如果字符数像您的情况一样受到限制,并且如果您在有效扇区之外按下,则光标将放置在该扇区的右边缘。

如果您希望发生这种情况,那么您必须在 mousePressEvent 中实现该逻辑:

class LineEdit: public QLineEdit
{
public:
    using QLineEdit::QLineEdit;
protected:
    void mousePressEvent(QMouseEvent *event)
    {
        QLineEdit::mousePressEvent(event);
        setCursorPosition(0);
    }
};

如果您想在您的 .ui 中使用 QLineEdit,那么您必须为此推广它,您可以查看以下出版物:

实现相同逻辑的另一种方法是使用事件过滤器:

*.h

class YourClass: public Foo{
// ...
public:
    bool eventFilter(QObject *obj, QEvent *event);
};

*.cpp

    // constructor
    ui->setupUi(this);
    ui->engineCapacity_lineEdit->installEventFilter(this);
    // ...

bool YourClass::eventFilter(QObject *obj, QEvent *event){
    if(obj == ui->engineCapacity_lineEdit && event->type() == QEvent::MouseButtonPress)
    {
        ui->engineCapacity_lineEdit->setCursorPosition(0);
    }
    return Foo::eventFilter(obj, event);
}

关于c++ - inputMask 用空格填充 QLineEdit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248611/

相关文章:

c++ - 如何修复错误 "clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)"?

c++ - 来自梯度图像的邻接矩阵

python - 使用修改键在 pyqt4 中拖放

c++ - Qt 基类函数定义

Qt 4.6 QLineEdit样式。如何设置灰色高光边框的圆角?

qt - 如何将图标放在 QLineEdit 上?

c++ - 每次调用方法时增加变量

c++ - 使用 intel 编译器编译 boost 1.57

c++ - 编译 Qt 应用程序以获得更好的调试信息 (Linux)

c++ - 无法从 QLineEdit 检索文本值