Qt 结束线程问题、按钮与事件关联问题。
//定义一个线程类,cpp文件#include"thread.h"#include<stdio.h>Thread::Thread(QObject*parent):QThr...
//定义一个线程类,cpp文件
#include "thread.h"
#include <stdio.h>
Thread::Thread(QObject *parent) :
QThread(parent)
{
}
void Thread::stop(Thread &thr)
{
thr.terminated();
}
void Thread::run()
{
}
#include "threaddialog.h" //cpp 文件
#include "ui_threaddialog.h"
#include <QRect>
ThreadDialog::ThreadDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ThreadDialog)
{
ui->setupUi(this);
}
ThreadDialog::~ThreadDialog()
{
delete ui;
}
void ThreadDialog::on_pushButtonA_clicked() //按钮A 按下槽函数
{
if(threadA.isRunning())
{
threadA.stop(threadA); //stop自己定义的
ui->pushButtonA->setText("start A");
ui->textEditMes->insertPlainText("A running stop... \n");
}
else
{
threadA.start();
ui->pushButtonA->setText("stop A");
ui->textEditMes->insertPlainText("A running start... \n");
ui->textEditMes->update();
}
}
void ThreadDialog::stop(Thread &thr)
{
threadA.stop(thr);
}
void ThreadDialog::closeEvent(QCloseEvent *e)
{
threadA.wait();
e->accept();
}
关于这段代码有两个问题: (1)在界面上有个按钮A,每次按钮按下都执行的是else后面部分,什么有原因? (2)在界面上有个退出按钮 怎样和事件closeEvent(QCloseEvent *e)关联,按下退出,没反应,什么原因? 展开
#include "thread.h"
#include <stdio.h>
Thread::Thread(QObject *parent) :
QThread(parent)
{
}
void Thread::stop(Thread &thr)
{
thr.terminated();
}
void Thread::run()
{
}
#include "threaddialog.h" //cpp 文件
#include "ui_threaddialog.h"
#include <QRect>
ThreadDialog::ThreadDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ThreadDialog)
{
ui->setupUi(this);
}
ThreadDialog::~ThreadDialog()
{
delete ui;
}
void ThreadDialog::on_pushButtonA_clicked() //按钮A 按下槽函数
{
if(threadA.isRunning())
{
threadA.stop(threadA); //stop自己定义的
ui->pushButtonA->setText("start A");
ui->textEditMes->insertPlainText("A running stop... \n");
}
else
{
threadA.start();
ui->pushButtonA->setText("stop A");
ui->textEditMes->insertPlainText("A running start... \n");
ui->textEditMes->update();
}
}
void ThreadDialog::stop(Thread &thr)
{
threadA.stop(thr);
}
void ThreadDialog::closeEvent(QCloseEvent *e)
{
threadA.wait();
e->accept();
}
关于这段代码有两个问题: (1)在界面上有个按钮A,每次按钮按下都执行的是else后面部分,什么有原因? (2)在界面上有个退出按钮 怎样和事件closeEvent(QCloseEvent *e)关联,按下退出,没反应,什么原因? 展开
1个回答
展开全部
1、既然执行else那么肯定是threadA.isRunning()为false,及线程没有运行,至于这个问题我感觉你慢慢试试吧!
2、关于退出问题很简单,既然你要重写closeEvent事件,那么你应该了解closeEvent执行的其实是在调用close函数的时候执行的,所以
(1)连接按钮信号和槽:QObject::connect(button, SIGNAL(clicked()), this, SLOT(makeClose()));
void ThreadDialog::makeClose()
{
this->close();
}
void ThreadDialog::closeEvent(QCloseEvent *e)
{
button->setText("close"); //点击按钮时候进行按钮文本的切换
..... //自己的事件
}
2、关于退出问题很简单,既然你要重写closeEvent事件,那么你应该了解closeEvent执行的其实是在调用close函数的时候执行的,所以
(1)连接按钮信号和槽:QObject::connect(button, SIGNAL(clicked()), this, SLOT(makeClose()));
void ThreadDialog::makeClose()
{
this->close();
}
void ThreadDialog::closeEvent(QCloseEvent *e)
{
button->setText("close"); //点击按钮时候进行按钮文本的切换
..... //自己的事件
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询