[英]How to keep background code running without create a thread?
UI like this: 这样的UI:
output like this: click 《output 1》, then change 0 to 1 输出如下:单击《输出1》,然后将0更改为1
here is the cpp code, I didnt add .h files: all files are available here jump to all code in github 这是cpp代码,我没有添加.h文件:所有文件都在这里可用跳转到github中的所有代码
#include "MainWindow.h"
#include <QApplication>
#include <iostream>
#include "deal.h"
int main(int argc, char *argv[])
{
std::cout << argc << " " << argv[0] << std::endl;
// getchar();
QApplication a(argc, argv);
MainWindow w;
w.show();
// getchar();
pthread_t tid; //Not want to create a thread to run this
pthread_create(&tid, NULL, run, NULL);
//pthread_exit(&tid);
a.exec();
return 0;
}
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "deal.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->pbOriginSound, SIGNAL(clicked()), this, SLOT(change2_origin_sound()));
connect(ui->pbVecSound, SIGNAL(clicked()), this, SLOT(change2_vec_sound()));
connect(ui->pbVecNrSound, SIGNAL(clicked()), this, SLOT(change2_vec_nr_sound()));
}
void MainWindow::change2_origin_sound(){
iFlag = 0;
printf("%d", iFlag);
}
void MainWindow::change2_vec_sound(){
iFlag = 1;
printf("%d", iFlag);
}
void MainWindow::change2_vec_nr_sound(){
iFlag = 2;
printf("%d", iFlag);
}
MainWindow::~MainWindow()
{
delete ui;
}
#include "deal.h"
#include <iostream>
#include <unistd.h>
int iFlag;
void *run(void *arg){
while(1){
// sleep(1);
printf("%d\n", iFlag);
printf("%d%d\n", iFlag, iFlag);
}
}
One common way is to create a slot-method and a QTimer that will call that method every so-many milliseconds, eg 一种常见的方法是创建一个槽方法和一个QTimer,它将每隔几毫秒调用该方法,例如
in MainWindow.h: 在MainWindow.h中:
#include <QTimer>
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
[...]
private slots:
void MySlot();
private:
QTimer myTimer;
};
in MainWindow.cpp: 在MainWindow.cpp中:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
[...]
connect(&myTimer, SIGNAL(timeout()), this, SLOT(MySlot()));
myTimer.start(100); // MySlot() will be called every 100mS
}
void MainWindow::MySlot()
{
printf("%d\n", iFlag);
}
Note that this approach assumes that MySlot()
will return quickly; 请注意,此方法假定MySlot()
将快速返回; if it doesn't, your GUI will freeze up until it returns, since MySlot()
is still running in the GUI thread and is therefore holding off the handling of other GUI events. 如果没有,您的GUI将冻结直到它返回,因为MySlot()
仍在GUI线程中运行,因此不会处理其他GUI事件。 So be sure not to do anything inside MySlot()
that takes a long time, unless you are willing to live with an not-very-responsive GUI. 因此,请确保不要在MySlot()
内部执行任何需要很长时间的事情,除非您愿意使用响应速度不高的GUI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.