繁体   English   中英

使用功能的QTimer? [Qt的]

[英]Using a QTimer for a function? [Qt]

我想在程序中运行的函数上设置QTimer 我有以下代码:

// Redirect Console output to a QTextEdit widget
new Q_DebugStream(std::cout, ui->TXT_C); 

// Run a class member function that outputs Items via cout and shows them in a QTextEdit widget
// I want to set up a QTimer like the animation below for this.
myClass p1;
p1.display("Item1\nItem2\nItem3", 200);

// show fading animation of a QTextEdit box after 1000 milliseconds
// this works and will occur AFTER the QDialog shows up no problem.
QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
ui->TXT_C->setGraphicsEffect(eff);
QPropertyAnimation* a = new QPropertyAnimation(eff,"opacity");
a->setDuration(2000);
a->setStartValue(.75);
a->setEndValue(0);
a->setEasingCurve(QEasingCurve::OutCubic);
QTimer::singleShot(1000, a, SLOT(start()));

myClass.cpp

myClass::myClass()
{}

int myClass::display(std::string hello, int speed)
{
  int x=0;
  while ( hello[x] != '\0')
  {
    std::cout << hello[x];
    Sleep(speed);
    x++;
  };
    std::cout << "\n\nEnd of message..";
    return 0;
}

我想让第一部分( p1.display(...); )像第二个动画一样工作,在第二个动画中,我设置了QTimer使其在设定的时间后显示。 我将如何去做呢?

理想情况下,我想要这样的东西:

QTimer::singleShot(500, "p1.display("Item1\\nItem2\\nItem3", 200)", SLOT(start()));

这段代码显然无法理解,也行不通,但希望可以为我想做的事情指明重点。 先感谢您。

基本解决方案

您可以从调用类中调用插槽(看不到代码中的名称),就像第二个动画一样(必须添加slot函数):

QTimer::singleShot(500, this, SLOT(slotToCallP1Display()));

然后添加插槽功能:

void whateverThisTopLevelClassIsCalled::slotToCallP1Display()
{
   myClass p1;
   p1.display("Item1\nItem2\nItem3", 200);
}

qt 5.5 / c ++ 11

我相信您可以做这样的事情(使用lambda创建函子):

myClass p1;
QTimer::singleShot(500, []() { p1.display("Item1\nItem2\nItem3", 200); } );

我尚未测试此代码,但最近做了类似的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM