qt输入控件限制输入类型

限制输入类型

有两个控件,根据第一个控件的类型,限制第二个控件可以输入的值

代码

QComboBox comboBox;
comboBox.addItem("字符串");
comboBox.addItem("数字");
layout.addWidget(&comboBox);

// 连接信号与槽
QObject::connect(&comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [&](int index){
    if(index == 0) { // 如果选择的是字符串
        input.setValidator(nullptr); // 清除之前的验证器
        // 设置字符串验证器
        input.setInputMask(""); // 清除之前的输入掩码
    } else if(index == 1) { // 如果选择的是数字
        // 创建整数验证器
        QIntValidator *validator = new QIntValidator(&input);
        // 设置验证范围
        validator->setRange(-10000, 10000);
        input.setValidator(validator); // 设置验证器
        input.setInputMask(""); // 清除之前的输入掩码
    }
});
posted @ 2024-03-07 10:03  卑以自牧lq  阅读(123)  评论(0)    收藏  举报