【发布时间】:2020-11-09 06:32:30
【问题描述】:
所以我在下面有一个简单的类,它使用 QTimer 每 1 秒向总数添加一个数字:
// score.h
#include <QObject>
#include <QTimer>
class Score : public QObject
{
Q_OBJECT
public:
explicit Score(QObject *parent = nullptr);
void start();
void stop();
QTimer *timer;
int getScore();
private slots:
void update();
private:
int score;
};
// score.cpp
#include "score.h"
Score::Score(QObject *parent) : QObject(parent)
{
score = 0;
timer = new QTimer(this);
}
void Score::start()
{
timer->start(1000);
}
void Score::stop()
{
timer->stop();
}
int Score::getScore()
{
return score;
}
void Score::update()
{
score += 10;
qDebug() << score;
}
// main.cpp
#include <QCoreApplication>
#include "score.h"
#include <QtDebug>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Score score{};
std::string input{""};
while(input!="1") {
std::cout << "1. to stop" << std::endl;
std::cout << "2. to start" << std::endl;
std::cin >> input;
if(input=="1") {
score.stop();
}
else if(input=="2") {
score.start();
}
}
return a.exec();
}
在循环过程中,如果我按下如果我的输入是 2,则什么也没有发生。该插槽似乎没有触发,因为我没有看到任何输出到控制台的内容。一般来说,我对 QT 很陌生,所以我可能做错了什么。另一个想法是我认为这可能是由于一些线程问题。但是我之前没有太多线程方面的经验。
【问题讨论】:
-
在您启动
a.exec()之前计时器无法触发。它包含管理计时器的事件循环(除其他外)。您必须了解如何通过QCoreApplication事件处理控制台输入。如果我选择 Qt,我这样做是为了开发 GUI 应用程序(其中输入只是对小部件事件的反应)。如果我想做控制台应用程序,我不会选择 Qt。仅供参考:I/O in concurrent program(使用多线程,您可以同时处理用户输入和计时器,尽管您仍然必须使用非标准非阻塞输入。)