使用 QThread 显示构建问题的延时

Time delay using QThread showing build issues

本文关键字:问题 构建 QThread 显示 使用      更新时间:2023-10-16

我正在尝试实现 QT Qthread 的睡眠功能,所以我在头文件中将其声明为 --

namespace Ui {
    class MainWindow;
}
class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
    static void sleep(unsigned long secs){QThread::sleep(secs);}
protected:
    void changeEvent(QEvent *e);
private:
    Ui::MainWindow *ui;
private slots:
    void on_pushButton_clicked();
};

在我的源代码中,我正在做的是在连接到数据库后,我想要一个标签来更改背景颜色(有点像发光效果),所以我尝试从 while(true) 循环中调用 sleep 函数。

while(db.open())
{
    MainWindow::sleep(13);
    qDebug()<<"Success ";
    ui->glow_label->setStyleSheet("QLabel {background-color: rgb(0, 255, 0);}");
    MainWindow::sleep(5);
    ui->glow_label->setStyleSheet("QLabel {background-color: rgb(0, 85, 255);}");
}

但它在构建时显示错误 ->

/

usr/local/Trolltech/Qt-4.8.4/include/QtCore/qthread.h:115:错误:"static void QThread::sleep(long unsigned int)"受保护/home/aj/MY_QT_WORK/timer_test/mainwindow.h:22:错误:在此上下文中

我做错的任何想法???

在主线程中使用sleep()是个坏主意,因为它会阻止所有GUI线程。此外,Qt测试库对于生产来说太重了。因此,请尝试仅使用QTimer或尝试类似操作:

void sleep(qint64 msec)
{
    QEventLoop loop;
    QTimer::singleShot(msec, &loop, SLOT(quit()));
    loop.exec();
}

你可以在这里找到问题的答案:如何使用Qt创建暂停/等待函数? .如果你对为什么QThread::sleep()受到保护而你不能使用它感兴趣,答案很简单。QThread::sleep() 被实现,以便它只能在调用它自己的线程中进行延迟。因此,此方法可以在多线程应用程序中使用,以将一个线程延迟一段时间。要指定要延迟的线程,只能从该线程代码调用此方法。这就是它受到保护的原因。

切勿在 GUI 线程中使用 while(true) 或类似内容。摆脱使用任何类型的睡眠函数的整个想法,并使用带有状态的计时器来创建发光动画。

enum GlowState{StateGreen, StateBlue}; // declare an enum somewhere in your class header
GlowState _animState; // declare a private member variable somewhere in your header
void MyClass::animateLabel() // create a slot in your class
{
    switch(_animState)
    {
    case StateGreen:
        myLabel->setStyleSheet("QLabel {background-color: rgb(0, 255, 0);}");
        _animState = StateBlue;
        QTimer::singleShot(5, this, SLOT(animateLabel()));
        break;
    case StateBlue:
        myLabel->setStyleSheet("QLabel {background-color: rgb(0, 0, 255);}");
        _animState = StateGreen;
        QTimer::singleShot(13, this, SLOT(animateLabel()));
        break;
    }
}

在某个位置调用animateLabel槽以开始动画。不过,在调用它之前设置_animState起始值。您还可以创建StateStartStateStop状态以使其更清晰(并能够停止动画)。