线程指针不能正确显示,求师傅我想自己设计一个类似时间的界面能显示,但是不能递加显示,我用QTime能够实现,
线程指针不能正确显示,求师傅
我想自己设计一个类似时间的界面能显示,但
是不能递加显示,我用QTime能够实现,现在想换一种方法,请问有什么办法可以修改代码
这个是线程代码
#include "mythread.h"
#include "ui_mydialog.h"
#include <QtGui/QtGui>
extern int global_sec;
extern int global_min;
extern int global_hour;
extern int flag;
void MyThread::run()
{
global_min = 59;
global_hour = 11;
global_sec = 55;
while(1)
{
global_sec = (global_sec+1)%60;
if( global_sec == 0)
{
global_min = (global_min+1)%60;
if ( global_min == 0)
{
global_hour = (global_hour+1)%24;
}
}
if( flag == 0)
{
qDebug("%d:%d:%d",global_hour,global_min,global_sec);
ui->sLineEdit->setText(QString::number(global_sec));//我想让他在这里循环显示,怎么修改
}
else
break;
sleep(1);
}
}
//.cpp
#include "mydialog.h"
#include "ui_mydialog.h"
#include "mythread.h"
#include <QTimer>
int global_sec;
int global_min;
int global_hour;
int flag = 0;
myDialog::myDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::myDialog)
{
ui->setupUi(this);
ui->hLineEdit->setReadOnly(true);
ui->mLineEdit->setReadOnly(true);
ui->sLineEdit->setReadOnly(true);
connect(ui->runButton,SIGNAL(clicked()),this,SLOT(display()));
connect(ui->runButton,SIGNAL(clicked()),this,SLOT(runclicked()));
connect(ui->pauseButton,SIGNAL(clicked()),this,SLOT(runpause()));
connect(ui->clearButton,SIGNAL(clicked()),this,SLOT(runclear()));
}
myDialog::~myDialog()
{
delete ui;
}
void myDialog::runclicked()
{
MyThread *mytime = new MyThread;
mytime->start();
}
void myDialog::display()
{
ui->hLineEdit->setText(QString::number(global_hour));
ui->mLineEdit->setText(QString::number(global_min));
ui->sLineEdit->setText(QString::number(global_sec));
}
void myDialog::runpause()
{
flag = 1;
}
void myDialog::runclear()
{
ui->hLineEdit->clear();
ui->mLineEdit->clear();
ui->sLineEdit->clear();
}
[解决办法]
点击开始,把时分秒换算成秒,用个类成员变量,int totleSecs;
在线程里做个信号,每一秒发射一个信号,然后在GUI线程里面接收这个信号,
privte slots:
void timePassBy();
void timePassBy()
{
totleSecs --;
然后把totleSecs 转为时分秒显示在界面上
}
记住:QT不建议(客气的说法)在非GUI线程里面修改界面,如果在非主线程(GUI线程)修改GUI,就会出问题。