Congratulations to our 2022 Qt Champions!

[SOLVED]QTimer in a Class - Problem

  • Hello dear community,
    Before I start explaining my problem I would like to introduce myself since this is my very first post here :)!
    I'm a developer for automatic "botting systems" for online games and experienced with Assembly/Python/C++ and a bit with C#.

    Now let me explain my problem:

    For example I've created a fresh Qt Widgets Application with a QWidget and a class.

    Here are my classes:
    // mywidget.h //

    // mywidget.cpp //

    // myclass.h //

    // myclass.cpp //

    And the main (I don't think it's important but here):

    I commented the code where I have trouble and FYI the code compiles fine but the Slot from the QTimer in the Class "myclass" is not being executed. Other than that the Slot in the "mywidget" class is working fine.
    I hope that some people can help me and maybe even others who have the same issue. I hope everything is clear and please don't judge me and the code, I'm really new to Qt :).

    Edit: My target is to execute a function in a QTimer from another class when I click pushButton.

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Your MyClass instance in on_pushButton_clicked will only live as long as the line it's created on till then end of the method. So basically, it's destroyed right after it's created.

  • First of all thanks for the fast answer!

    Hmm.. but if that's the case then I still wonder how I can initialize the instance without destroying it directly?

  • Lifetime Qt Champion

    Before that, what exactly are you trying to achieve ? It's important to know to avoid using a hammer to solve a problem that requires a screwdriver.

  • Basically I want to create a QTimer in another class and call it from the button in the mywidget class.

  • Lifetime Qt Champion

    Then if you want to re-use it, just make a member of it of your MyWidget class

  • I'm sorry but I don't really get it what you mean. Could you provide me an example please?

  • Lifetime Qt Champion

    #ifndef MYWIDGET_H
    #define MYWIDGET_H
    #include <QWidget>
    #include <QTimer>
    #include <QMessageBox>
    #include "myclass.h"
    namespace Ui {
    class MyWidget;
    class MyWidget : public QWidget
        explicit MyWidget(QWidget *parent = 0);
    private slots:
        void on_pushButton_clicked();
        Ui::MyWidget *ui;
        MyClass _myClass;
    #endif // MYWIDGET_H
    #include "mywidget.h"
    #include "ui_mywidget.h"
    MyWidget::MyWidget(QWidget *parent) :
        ui(new Ui::MyWidget)
        delete ui;
    void MyWidget::on_pushButton_clicked()

  • Thank you so much for your great help it worked fine!
    Now I understand why it had to be declared in the mywidget thx!

    #Can be closed [SOLVED]

Log in to reply