QT在运行时更新Linedit

QT update Linedit at runtime

本文关键字:Linedit 更新 运行时 QT      更新时间:2023-10-16

我试图更新我的linedit上的文本每次我得到一个帧,但我的程序崩溃。我试着用循环做同样的事情,但是窗口只在循环完成后显示。setH()是我的插槽,在调试模式下它运行完美,问题是当程序运行时(主窗口在屏幕上)试图更新LineEdit中的文本。谢谢你

void MainWindow::updatehand(){
    if (controller.isConnected()){
    int hc =frame.hands().count();
    QString hndc= QString::number(hc);
    emit hChanged(hndc);
}
void MainWindow::setH(const QString hndc){
    handsRead->setText(hndc);
    updatehand();
}

这就是崩溃的原因:

connect(this, SIGNAL(hChanged(const QString)), this, SLOT(setH(const QString)));

这种连接实际上是一个直接的函数调用。调用函数setH()代替emit hChanged(hndc);。然后从setH()调用updatehand()函数。

这是一个无限循环,堆栈溢出崩溃。


如果你想每秒调用updatehand() 60次,可以使用QTimer调用,例如使用QTimer static member:

void MainWindow::setH(const QString hndc){
    handsRead->setText(hndc);
    QTimer::singleShot(1000 / 60, this, SLOT(updatehand()));
}

这里updatehand()也是一个槽。

在这种情况下,偶数循环在从setH()返回后继续调度UI消息。

大约16毫秒后,计时器将调用updatehand()


上述解决方案在技术上打破了无限交叉引用循环。然而,它可以做得更好。存在外部调用者多次触发setH()的风险。在这种情况下,许多计时器将被激活。看起来您只需要一个QTimer实例来周期性地独立于setH()调用updatehand()。因此,updatehand()可以与给定时间段的更新数据合用。它可以直接调用setH(), setH()函数只设置QLineEdit文本:

void MainWindow::setH(const QString hndc){
    handsRead->setText(hndc);
}