为什么Qt中的close方法无法正常工作?

时间:2018-02-19 05:57:53

标签: qt usb exit

我在Qt编码。我与赛普拉斯FX2LP进行USB通信。当设备未通过USB电缆连接时,我应该显示一个带有OK-Abort选项的对话框。当用户点击确定时,我重新检查USB连接。它运作良好。但是当用户点击中止时,我应该完全关闭程序。中止选项不起作用并重新显示OK-Abort对话框。我的代码有什么问题? 这是我的代码的一部分(Main.cpp / Mainwindow / My_Receive_Data_Thread(我的USB通信线程)):

Main.cpp的:

#include "mainwindow.h"
#include <QApplication>
#include <QTimer>
#include <QIcon>

int main(int argc, char *argv[]){
    QApplication a(argc, argv);
    a.setQuitOnLastWindowClosed(true);
    a.processEvents();
    MainWindow w;
    w.setAttribute(Qt::WA_QuitOnClose);
    w.show();
    return a.exec();
}

My_Receive_Data_Thread:

My_Receive_Data_Thread::~My_drawing_object(){
}
void My_Receive_Data_Thread::Send_command_packet(){
    CCyUSBDevice USBDevice;// CCyUSBDevice recognize only Cypress Devices
    short int numDevices = USBDevice.DeviceCount();
    if(numDevices==0)
        emit show_message("warning","USB Device not connected!");
}

主窗口:

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),ui(new Ui::MainWindow){
    ui->setupUi(this);
    My_Receive_Data_Thread_1= new My_Receive_Data_Thread(this);
    connect(My_Receive_Data_Thread_1,SIGNAL(show_message(QString,QString)),this,SLOT(show_message_box(QString,QString)),static_cast<Qt::ConnectionType>(Qt::UniqueConnection));
    connect(this,SIGNAL(Send_command_packet()),My_Receive_Data_Thread_1,SLOT(Send_command_packet()),static_cast<Qt::ConnectionType>(Qt::UniqueConnection));
}
MainWindow::~MainWindow(){
    delete ui;
}
void MainWindow::show_message_box(QString title,QString text){
    QMessageBox::StandardButton reply; 

 reply=QMessageBox::question(this,title,text,QMessageBox::Abort|QMessageBox::Ok);
   if(reply==QMessageBox::Abort)
      close();
}

1 个答案:

答案 0 :(得分:0)

Send_command_packet()可能会被多次调用,因此它会排出很多已排队的show_message()

他们中的第一个将调用排队到close(),但还有其他show_message()要处理。

bool m_closed添加MainWindow,在结束时将其设置为true,然后在show_show_message_box()中进行检查。

void MainWindow::show_message_box(QString title,QString text){
    if (!m_closing){
        QMessageBox::StandardButton reply; 

        reply=QMessageBox::question(this,title,text,QMessageBox::Abort|QMessageBox::Ok);
        if(reply==QMessageBox::Abort){
            m_closing = true;
            close();
        }
    }
}
相关问题