我试图在每次获得帧时更新 linedit 上的文本,但我的程序崩溃了。我尝试用循环做同样的事情,但窗口只在循环完成后显示。 setH() 是我的插槽,在 Debug模式下它运行完美,问题是在程序运行时尝试更新 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
statics memember :
void MainWindow::setH(const QString hndc){
handsRead->setText(hndc);
QTimer::singleShot(1000 / 60, this, SLOT(updatehand()));
}
这里的updatehand()
也是一个slot。
在这种情况下,偶数循环会在 setH()
返回后继续发送 UI 消息。
大约 16 毫秒后,计时器将调用 updatehand()
。
上述解决方案在技术上打破了无限交叉引用循环。但是,它可以做得更好。 setH()
有被外部调用者多次触发的风险。在那种情况下,许多计时器将被激活。
看起来您只需要一个 QTimer
实例即可独立于 setH()
定期调用 updatehand()
。因此,updatehand()
可以在给定时间段内合并以更新数据。可以直接调用setH()
,setH()
函数只设置QLineEdit
文本:
void MainWindow::setH(const QString hndc){
handsRead->setText(hndc);
}
关于c++ - QT 在运行时更新 Lineedit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32750047/