Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

'insert' method of a QLineEdit object doesn't delete selected text



  • Hello, I'm looking for help to solve a problem with QLineEdit.

    When I press a special button the following char sequence is set on the QLineEdit object:

    add($,$)
    Each $ character is a placeholder for an int, which I'm supposed to provide by clicking on the [0-9] buttons. Each click inserts a new digit until I press Enter. Then the cursor moves to the second placeholder, selects it and wait for my click. But there is a problem.

    When add($,$) appears, I select the first placeholder and the program wait for the first digit which further substitutes the placeholder by itself. But when I finish entering the first number and move on to entering the second number each new digit doesn't erase the $ char, it just shifts it right. I tried almost everything I could imagine and it still doesn't work.

    Can anyone help with an advice please? Here is the code:

    void MainWindow::operation_clicked()
    {
        QString operation((qobject_cast<QPushButton*>(sender()))->text());
        if(operation == "add($,$)")
        {
            ui->lineEdit->insert(operation);
            ui->lineEdit->cursorBackward(false, 3);
            ui->lineEdit->setSelection(ui->lineEdit->cursorPosition(),-1);
        }
    }
    ```
    
    ```
    void MainWindow::digit_clicked()
    {
        if(expected_operands != 0 && printed_digits < MAXLEN)
        {
            QString num((qobject_cast<QPushButton*>(sender()))->text());
            ui->lineEdit->insert(num);
            ui->lineEdit->setFocus();
            ++printed_digits;
        }
    }
    ``
    
    ```
    void MainWindow::enter_pressed()
    {
        if(expected_operands != 0)
        {
            ui->lineEdit->setSelection(ui->lineEdit->cursorPosition(), (-printed_digits-sign));
            current_argument = (QString(ui->lineEdit->selectedText())).toInt();
            --expected_operands;
            ui->lineEdit->deselect();
            if(expected_operands != 0)
            {
                ui->lineEdit->cursorForward(false, sign+printed_digits+2);
                ui->lineEdit->setSelection(ui->lineEdit->cursorPosition(),-1);
            }
            ui->lineEdit->setFocus();
            printed_digits = 0;
        }
    }
    
    ````
    Everything is realised using SIGNAL-SLOT mechanism.

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Can you reduce that to a minimal compilable example that shows the behaviour ?


Log in to reply