I make a window with a PIN. There is a following kind: initially in lineedit there is a line like "_ _ _ _". Next, we replace each underscore with a number that is entered from the virtual keyboard, and, for example, has the following form - "1 2 _ _". After a split second, you need to replace the numbers with asterisks and get "* * _ _". Those. when you enter the numbers, we see her and she hides behind a star.

There is the following slot:

 void uRent::s1(const QString &i) { QString line = ui->lineEdit->text(); int index = line.indexOf('_'); line.replace(index, 1, i); ui->lineEdit->insert(line); QThread::msleep(1000); line.replace(index, 1, '*'); ui->lineEdit->setText(line); } 

But when he performs, he waits a second and then instead of the number he immediately inserts an asterisk. There is a suspicion that QThread::msleep(1000); it is performed not in the middle of the slot body, but immediately and only then all functions are performed. Is this true and how can you implement the above?

    1 answer 1

    When a new value is set in QLineEdit , the QPaintEvent event is created and sent to the corresponding widget. Calling the QThread::msleep() method blocks the delivery of the object of the indicated event.

    Total, it turns out:

    1. the first event with the figure is created and sent to the event dispatcher;
    2. sleep() locks the widget to redraw;
    3. the second event with an asterisk is created and sent to the event dispatcher;
    4. Both events are performed immediately after each other, which does not allow to see the changes by eye.

    Change your code to something using a timer. For example:

     void uRent::s1(const QString &i) { QString line = ui->lineEdit->text(); int index = line.indexOf('_'); line.replace(index, 1, i); ui->lineEdit->insert(line); QTimer *timer = new QTimer(this); timer->setSingleShot(true); timer->setInterval(500); connect(timer, &QTimer::timeout, [this,timer,index]() { QString line = ui->lineEdit->text(); line.replace(index, 1, '*'); ui->lineEdit->setText(line); timer->deleteLater(); }); timer->start(); } 
    • Thanks, I will try! - Madisson
    • @Madisson, please. - alexis031182
    • Tell me, what is this expression [this, timer, index] () and where can you read about it? I first meet this way of describing the slot. - Madisson
    • This is an anonymous (lambda) function. You can read about it, for example, here as a whole in C ++ and here in Qt . - alexis031182