如何使用QTimer每隔10秒将消息打印到QTextBrowser? [英] How to use QTimer to print a message to a QTextBrowser every 10 seconds?

查看:323
本文介绍了如何使用QTimer每隔10秒将消息打印到QTextBrowser?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经工作了几个小时,无法弄清楚,也找不到在线有效的帮助.基本上,我要完成的要旨是拥有一个带有按钮和QTextBrowser的Qt GUI.当我按下按钮时,我希望它显示一条消息,然后每隔10秒钟继续打印此消息.

I have working at this for hours and cannot figure it out nor can I find any help online that works. Basically the gist of what I am trying to accomplish is to have a Qt GUI with a button and a QTextBrowser. When I push the button I want it to display a message and then keep printing this message every 10 seconds.

我认为我会使用QTimer,因为有意义的是有一个计时器每10秒显示一次消息.当我最初将其实现到我的`buttonClicked()SLOT中时,它导致程序冻结.我在网上寻找解决方案,并找到了QApplication :: processEvents().

I figured I would use QTimer because it makes sense to have a timer to display the message every 10 seconds. When I originally implemented this into my `buttonClicked() SLOT it caused the program to freeze. I looked online for a solution and found QApplication::processEvents().

所以基本上在我的函数中我有这样的东西:

So basically in my function I had something like this:

while(1)
{
   QTimer *timer;
   connect(...)  //omitted parameters for this example     
   timer.start(10000);
   ui->diplay->append("Message");

   while(timer.isActive())
   {
      QApplication::processEvents() 
   }
}

我认为它会在while循环中打破timer.isActive()的作用,但它不会仅仅停留在其中.

I figured it would break out of the timer.isActive() while loop but it won't it simply stays in there.

所以我认为这是一个线程问题.因此,我想出了如何使用QThreads,但仍然无法使其正常工作.基本上,当我创建一个带有计时器的线程并且该线程告诉计时器启动时,程序将关闭,并且控制台会显示程序意外完成".

So I figured this is a threading issue. So I figured out how to use QThreads but I still can't get it to work. Basically when I create a thread with a timer on it and the thread tells the timer to start, the program closes and the console says "The program has unexpectedly finished".

必须有一种简单的方法来完成此操作,但是我在Qt的往绩一直是这样

There has to be an easy way to do this but my track record with Qt has always been that th

推荐答案

如果要显示10秒钟的消息,更好的方法是在应用程序中创建一个插槽,以清除消息.然后,在您单击按钮的插槽中,添加您的消息并初始化一个计时器,该计时器将在10秒内触发您删除消息的插槽:

If you want to display your message for 10s, the better way to do that, is to create a slot in your application that will erase the message. Then, in your button clicked slot, add your message and initialize a timer which will trigger your remove message slot in 10s:

QTimer::singleShot(10000, this, SLOT(eraseMessageSlot()));

此外,那里不需要线程...

Also, there is no need for a thread there...

这篇关于如何使用QTimer每隔10秒将消息打印到QTextBrowser?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆