我想通过UDP协议获取消息。如果我在try-catch块中创建了一个使用QUdpsocket的对象,则信号readyread((不起作用。但如果我在try-catch块之外创建了UDPworker的对象,那么一切都可以。我在异常和Qt组合中做了什么没有纠正?它是关于实现QUdpsocket的吗?
main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QtDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//MyUDP m_UDP; // its work
try
{
MyUDP m_UDP; // its not work! WHY?!
}
catch(...)
{
qDebug()<< "Unknown exception cautch!!!" << endl;
}
return a.exec();
}
pr.pro
QT += core gui network
CONFIG += c++14 console
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = untitled
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES +=
main.cpp
mainwindow.cpp
HEADERS +=
mainwindow.h
FORMS +=
mainwindow.ui
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
MyUDP::MyUDP(QObject *parent) :
QObject(parent)
{
socket = new QUdpSocket(this);
socket->bind(QHostAddress::LocalHost, 6650);
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
}
主窗口.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QUdpSocket>
#include <QMessageBox>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
//Base class QObject
class MyUDP : public QObject
{
Q_OBJECT
public:
explicit MyUDP(QObject *parent = 0);
void SayHello();
public slots:
void readData(){
QMessageBox::information(0, "Внимание","Это очень важный текст", 0,0,0);
}
private:
QUdpSocket *socket;
};
#endif // MAINWINDOW_H
您在try块内创建MyUDP,没有捕获任何错误或超出try/catch范围,因此MyUDP开始被销毁:
try {
MyUDP m_UDP; // Created in the stack, valid only inside the try block
}
catch (...)
{
}
//m_UDP is already destroyed and undefined here
我应该补充一点,您使用的是QObjects和信令/插槽机制,而不是以预期/正统的方式,但这超出了您的问题。您应该阅读有关QObject和信号/插槽机制的文档,Qt在联机和QtAssistant应用程序中都有大量信息。