让QTimer公开。 (Qt,C ++)

时间:2012-02-25 23:13:50

标签: c++ qt timer public

我有QMainWindow连接2个按钮和2个功能。我想使用StartBTNClick函数启动QTimer并使用StopBTNClick函数停止QTimer。我的问题是,QTimer没有在StopBTNClick中定义,这就是我想知道如何定义公共QTimer的原因。 (顺便说一句。我是C ++的新手,请耐心等待我)

到目前为止,这是我的代码:

MyClass::MainWindow(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);
    statusBar()->showMessage("Status: Idle.");
    connect(ui.StartBTN, SIGNAL(clicked()), this, SLOT(StartBTNClick()));
    connect(ui.StopBTN, SIGNAL(clicked()), this, SLOT(StopBTNClick()));
}

void MyClass::StartBTNClick()
{
    QTimer *RunTimer = new QTimer(this);
    connect(RunTimer, SIGNAL(timeout()), this, SLOT(TimerHandler()));
    RunTimer->start(5000);
    statusBar()->showMessage("Status: Running.");
}

void MyClass::StopBTNClick()
{
    RunTimer->stop(); // Not working. Says it's not defined.
    disconnect(RunTimer, SIGNAL(timeout()), this, SLOT(TimerHandler()));
    statusBar()->showMessage("Status: Idle.");
}

void MyClass::TimerHandler()
{
    // I set QMessageBox to test if it's working.
    QMessageBox::information(this, "lala", "nomnom");
}

1 个答案:

答案 0 :(得分:3)

使QTimer成为您班级的成员变量,并且可以在两个函数中访问它。

class MyClass
{
... //other variables and method definitions

QTimer* runTimer;
};

使用类成员指针,而不是本地定义的指针:

void MyClass::StartBTNClick()
{
    runTimer = new QTimer(this);//this would work, but it may be better to
                                  //initialize the timer in the constructor
    connect(runTimer, SIGNAL(timeout()), this, SLOT(TimerHandler()));
    runTimer->start(5000);
    statusBar()->showMessage("Status: Running.");
}

void MyClass::StopBTNClick()
{
    runTimer->stop(); // this will work now; if it hasn't been initialized, though,
                      // you will cause a crash.
    disconnect(RunTimer, SIGNAL(timeout()), this, SLOT(TimerHandler()));
    statusBar()->showMessage("Status: Idle.");
}

在构造函数中初始化时间(runTimer = new QTimer(this))而不是单击按钮可能会更好,并且只需在单击按钮时启动计时器。如果你不这样做,你必须防止在StopBTNClick()中使用未初始化的指针,以防在开始按钮之前点击按钮。