使用QTimer函数? [Qt]
问题描述:
我想在我的程序中运行的函数上设置一个QTimer
。我有以下代码:使用QTimer函数? [Qt]
// 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()));
此代码显然不会makse感,也不会工作,但它希望得到的点对面的想什么,我做的。 预先感谢您。
答
,基本解决方案
可以从调用类调用一个插槽(什么也看不见它调用您的代码),就像你第二动画做的(你要添加的插槽功能) :
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); });
我没有测试此代码,但我没有类似的东西最近。
该lambda解决方案工作。我只需要在方括号中添加[&p1]。谢谢! – orbit
@orbit Oh yah +1,我对lambda格式有点废话,我没有多用它,因为它非常丑陋(imho)......但它有它的用处! :) –
小心lambda解决方案,你需要确保'p1'的存活时间足够长。 –