【问题标题】:Problems with function QTimer::singleShot函数 QTimer::singleShot 的问题
【发布时间】:2013-07-28 16:22:02
【问题描述】:

我正在尝试通过 QAudioInput 录制声音。根据本网站上的文档QAudioInput。但是当我运行时,它导出了一个空的原始文件。检查后,似乎函数 QTimer::singleShot 不起作用(我在 void stopRecording() 中添加了声明 qWarning << "Done" 并且它没有显示“完成”所以我认为它在 QTimer::singleShot 函数中有一些错误) .

这是我用来检查函数 QTimer::singleShot 的代码

----Check.pro----
QT += core
QT -= gui
TARGET = Check
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
HEADERS += test.h

-----test.h------
#ifndef TEST_H
#define TEST_H

#include <QCoreApplication>
#include <QTimer>
#include <iostream>
#include <QObject>
#include <test.h>
#include <QDebug>

using namespace std;

class Object: public QObject {
   Q_OBJECT
private slots:
  void func() { cout << "Hello"; }
};

#endif // TEST_H

----main.cpp----
#include <QCoreApplication>
#include <QTimer>
#include <iostream>
#include <QObject>
#include <test.h>
#include <QDebug>

using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Object *o = new Object;
    QTimer::singleShot(10000, o, SLOT(func()));
    return 0;
}

而且这段代码也不起作用。谁能解释我?我是 Qt 编程的新手。

【问题讨论】:

    标签: qt qtimer


    【解决方案1】:

    您的程序在设置计时器后立即退出 - 它没有时间触发。

    要使计时器工作,您需要运行一个事件循环。如果没有事件循环,则不会处理任何事件。

    main 的最后一行更改为

    return a.exec();
    

    还可以通过添加&lt;&lt; std::endl 或刷新std::cout 来更改您的测试槽,否则您可能会在控制台上看不到任何输出。

    然后您的程序应该按预期工作(除非它永远不会完成,因为没有什么会导致事件循环停止 - 只需中断它)。

    【讨论】:

    • 哦,我明白了。所以我必须创建一个事件循环才能使该功能有效?谢谢:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多