使用 QThread 显示构建问题的延时
Time delay using QThread showing build issues
我正在尝试实现 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
起始值。您还可以创建StateStart
和StateStop
状态以使其更清晰(并能够停止动画)。
- 如何解决 Ninja c++ 构建和执行问题
- macOS 上的 openvino 构建问题
- 在树莓派上用libtorch构建程序时的链接问题
- 使用 MinGW 在 Windows 上构建 GLEW 时遇到问题
- 构建LLVM 10 C++工具链的问题
- 在Visual Studio 2017中使用c ++组件构建python解决方案时出现问题
- 调试模板时出现问题.专门针对 Linux GCC 7、GCC 6、GCC 5、GCC 4.9 错误构建失败:模板参数 1
- 构建OpenCV的基本CMakefile问题
- wxWidgets jpeg库构建问题
- exteranl原生构建问题,构建命令失败,android工作室
- 使用 Bazel (Windows) 构建 Tensorflow 的问题 => 使用 Tensorflow C++ API
- 使用 CMake 构建 {fmt} 时出现问题
- 使用 RcppArmadillo 构建 R 包的问题
- 使用 cmake 构建 dOxygen 的问题
- PCL 构建存在 boost::throw_exception 问题
- TFS构建由于链接问题而失败
- 构建Makefile的问题
- 修复了安装 OSRM 时使用"make"命令时的构建问题
- 在 MATLAB 上使用 G++ 构建时出现问题
- 在构建基于 C++ 的软件时包含 QtGui 文件的问题