earth
earth

Reputation: 955

Using a QTimer for a function? [Qt]

I would like to set a QTimer on a function that gets run in my program. I have the following code:

// 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;
}

I would like to get the first part (p1.display(...);) to work just like the second animation where I set up a QTimer for it to show up after a set amount of time. How would I go about doing this?

Ideally, I would want something like:

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

This code obviously doesn't makse sense and won't work, but it hopefully gets the point across for what I'd like to do. Thank you in advance.

Upvotes: 3

Views: 2713

Answers (1)

code_fodder
code_fodder

Reputation: 16331

Basic solution

You can call a slot from the calling class (can't see what its called in your code) just like you do for the second animation (you have to add the slot function):

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

Then add the slot function:

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

qt 5.5 / c++11

I believe you could do somthing like this (using lambda to create a functor):

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

I have not tested this code, but I did something similar recently.

Upvotes: 5

Related Questions