QtCharts setRange issue - c++

I want to display some data using QtCharts. When I set my data then nothing is displayed. I think the problem is with the setRange method.
Code:
chart.h:
#ifndef CHART_H
#define CHART_H
#include <QChart>
#include <QTimer>
#include <QAbstractAxis>
#include <QSplineSeries>
#include <QValueAxis>
#include <QDebug>
QT_CHARTS_BEGIN_NAMESPACE
class QSplineSeries;
class QValueAxis;
QT_CHARTS_END_NAMESPACE
QT_CHARTS_USE_NAMESPACE
class Chart: public QChart
{
Q_OBJECT
public:
Chart(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
virtual ~Chart();
public slots:
void handleTimeout();
private:
QTimer m_timer;
QSplineSeries *m_series;
QStringList m_titles;
QValueAxis *m_axisX;
QValueAxis *m_axisY;
qreal m_step;
qreal m_x;
qreal m_y;
QList<double> testList;
};
#endif /* CHART_H */
chart.cpp:
#include "chart.h"
Chart::Chart(QGraphicsItem *parent, Qt::WindowFlags wFlags):
QChart(QChart::ChartTypeCartesian, parent, wFlags),
m_series(0),
m_step(0),
m_x(1),
m_y(1)
{
m_axisX = new QValueAxis(this);
m_axisX->setLabelsVisible(false);
m_axisY = new QValueAxis(this);
m_axisY->setLabelsVisible(false);
connect(&m_timer, &QTimer::timeout, this, &Chart::handleTimeout);
m_timer.setInterval(1000);
m_series = new QSplineSeries(this);
QPen green(Qt::green);
green.setWidth(3);
m_series->setPen(green);
m_series->append(m_x, m_y);
legend()->hide();
addSeries(m_series);
setAxisX(m_axisX, m_series);
setAxisY(m_axisY, m_series);
m_axisX->setTickCount(5);
testList << 93.8436 << 777.797 << 2507.78 << 5999.44 << 6806.54 << 7481.16
<< 8008.5 << 8093.8 << 8161.83 << 8216.99
<< 8280.46 << 8328.4 << 8394.55 << 8469.84
<< 8500.65 << 8558.16 << 8660.9 << 8638.87
<< 8726.47 << 8715.25 << 8804.48 << 8793.86
<< 8839.42 << 8875.75 << 8938.24 << 8977.09
<< 9020.27 << 9046.7 << 9092.04 << 9121.58
<< 9155.36 << 9199.46;
axisX()->setRange(0, 100);
axisY()->setRange(-1, 100);
m_timer.start();
}
void Chart::handleTimeout()
{
qreal x = plotArea().width() / m_axisX->tickCount();
qreal y = (m_axisX->max() - m_axisX->min()) / m_axisX->tickCount();
m_x += y;
if (!testList.isEmpty()) {
m_y = testList.first();
testList.takeFirst();
}
qDebug() << "m_x: " << m_x << " " << "m_y: " << m_y;
m_series->append(m_x, m_y);
scroll(x, 0);
}
Chart::~Chart()
{
}
main.cpp:
#include "chart.h"
#include <QChartView>
#include <QApplication>
#include <QWidget>
#include <QHBoxLayout>
QT_CHARTS_USE_NAMESPACE
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget window;
Chart *chart = new Chart;
//chart->setTitle("Dynamic spline chart");
chart->setAnimationOptions(QChart::AllAnimations);
QChartView chartView(chart);
chartView.setRenderHint(QPainter::Antialiasing);
chartView.resize(window.size());
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(&chartView);
window.setLayout(layout);
window.setMinimumSize(810, 400);
window.show();
return a.exec();
}
Any ideas how to fix it? Thanks.
[Updated]
I have fixed the issue. Now it works well, but I need to set the axis rect background color.
Screenshot:
Any ideas how to set the axis background color? Thanks.

I have fixed the issue by using QtNetworkMonitor example from GitHub. The issue is resolved.

Related

capture QVideoFrame and display it in QVideoWidget

I want capture from camera frames.
I setup ui, camera, and surface.
QtVideoWidgetsIssueTrack::QtVideoWidgetsIssueTrack(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
QCamera* mCamera = new QCamera();
QMediaRecorder* recorder = new QMediaRecorder(mCamera);
QVideoEncoderSettings settings = recorder->videoSettings();
QMyAbstractVideoSurface* surface = new QMyAbstractVideoSurface();
settings.setResolution(640, 480);
settings.setQuality(QMultimedia::VeryHighQuality);
settings.setFrameRate(30.0);
settings.setCodec("video/mp4");
recorder->setVideoSettings(settings);
recorder->setContainerFormat("mp4");
mCamera->setCaptureMode(QCamera::CaptureViewfinder);
mCamera->setViewfinder(surface);
// Set layout
QGridLayout* layout = new QGridLayout();
QVideoWidget* videoWidget = new QVideoWidget;
videoWidget->show();
// Set layout in QWidget
QWidget* window = new QWidget();
layout->addWidget(videoWidget);
window->setLayout(layout);
// Set QWidget as the central layout of the main window
setCentralWidget(window);
bool o = recorder->setOutputLocation(QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + "/" + "test_video"));
recorder->record();
mCamera->start();
qDebug() << o;
qDebug() << recorder->supportedVideoCodecs();
qDebug() << recorder->state();
qDebug() << recorder->error();
qDebug() << recorder->outputLocation();
}
QtVideoWidgetsIssueTrack::~QtVideoWidgetsIssueTrack()
{}
I have created QMyAbstractVideoSurface instance and set surface in camera.
#pragma once
#include <QtMultimedia/QAbstractVideoSurface>
class QMyAbstractVideoSurface : public QAbstractVideoSurface
{
Q_OBJECT
public:
explicit QMyAbstractVideoSurface(QObject* parent = 0);
~QMyAbstractVideoSurface();
QList<QVideoFrame::PixelFormat> supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const;
bool present(const QVideoFrame& frame);
bool start(const QVideoSurfaceFormat& format);
void stop();
};
Now the problem is capture QVideoFrame from present method and display it in QVideoWidget.
Then add QVideoWidget to grid layout.
#include "QMyAbstractVideoSurface.h"
#include <QDebug>
#include <QBuffer>
QMyAbstractVideoSurface::QMyAbstractVideoSurface(QObject* parent) {
}
bool QMyAbstractVideoSurface::start(const QVideoSurfaceFormat& format) {
return QAbstractVideoSurface::start(format);
}
void QMyAbstractVideoSurface::stop() {
QAbstractVideoSurface::stop();
}
bool QMyAbstractVideoSurface::present(const QVideoFrame& frame) {
if (frame.isValid()) {
QVideoFrame cloneFrame(frame);
QAbstractVideoBuffer::HandleType handleType;
cloneFrame.map(QAbstractVideoBuffer::ReadOnly);
qDebug() << cloneFrame;
const QImage image(cloneFrame.bits(),
cloneFrame.width(),
cloneFrame.height(),
QVideoFrame::imageFormatFromPixelFormat(cloneFrame.pixelFormat()));
QByteArray ba;
QBuffer bu(&ba);
//bu.open(QBuffer::ReadWrite);
bu.open(QIODevice::WriteOnly);
image.save(&bu, "PNG");
//bu.close();
//QString imgBase64 = ba.toBase64();
QString imgBase64 = QString::fromLatin1(ba.toBase64().data());
qDebug() << "image base64: " << imgBase64;
cloneFrame.unmap();
return true;
}
return true;
}
QList<QVideoFrame::PixelFormat> QMyAbstractVideoSurface::
supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const
{
Q_UNUSED(handleType);
return QList<QVideoFrame::PixelFormat>()
<< QVideoFrame::Format_ARGB32
<< QVideoFrame::Format_ARGB32_Premultiplied
<< QVideoFrame::Format_RGB32
<< QVideoFrame::Format_RGB24
<< QVideoFrame::Format_RGB565
<< QVideoFrame::Format_RGB555
<< QVideoFrame::Format_ARGB8565_Premultiplied
<< QVideoFrame::Format_BGRA32
<< QVideoFrame::Format_BGRA32_Premultiplied
<< QVideoFrame::Format_BGR32
<< QVideoFrame::Format_BGR24
<< QVideoFrame::Format_BGR565
<< QVideoFrame::Format_BGR555
<< QVideoFrame::Format_BGRA5658_Premultiplied
<< QVideoFrame::Format_AYUV444
<< QVideoFrame::Format_AYUV444_Premultiplied
<< QVideoFrame::Format_YUV444
<< QVideoFrame::Format_YUV420P
<< QVideoFrame::Format_YV12
<< QVideoFrame::Format_UYVY
<< QVideoFrame::Format_YUYV
<< QVideoFrame::Format_NV12
<< QVideoFrame::Format_NV21
<< QVideoFrame::Format_IMC1
<< QVideoFrame::Format_IMC2
<< QVideoFrame::Format_IMC3
<< QVideoFrame::Format_IMC4
<< QVideoFrame::Format_Y8
<< QVideoFrame::Format_Y16
<< QVideoFrame::Format_Jpeg
<< QVideoFrame::Format_CameraRaw
<< QVideoFrame::Format_AdobeDng;
}
QMyAbstractVideoSurface::~QMyAbstractVideoSurface()
{}
it display me this
QVideoFrame(QSize(640, 480), Format_YUYV, NoHandle, ReadOnly, [no timestamp])
image base64: ""

Cannot read bytes while recording audio using QAudioInput

I am using QAudioInput to record audio from the system default input device.
I get a callback from QIODevice::readyRead that bytes are ready for read, but reading the bytes return an array of \0 's, equal to the size of the audioInput->bytesReady().
What am I doing wrong here and I cannot get the actual bytes recorded from the device?
This is the complete code:
file main.cpp
#include "mainwindow.h"
#include "audiorecorder.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
AudioRecorder recorder;
recorder.startRecording();
return a.exec();
}
file audiorecorder.h
#ifndef AUDIORECORDER_H
#define AUDIORECORDER_H
#include <QObject>
#include <QAudioInput>
class AudioRecorder : public QObject
{
Q_OBJECT
public:
explicit AudioRecorder(QObject *parent = nullptr);
void startRecording();
private:
QAudioInput *audioInput;
QAudioDeviceInfo deviceInfo;
QAudioFormat format;
QIODevice *iodevice;
QAudioDeviceInfo devInfo;
void onReadyRead();
signals:
};
#endif // AUDIORECORDER_H
file audiorecorder.cpp
#include "audiorecorder.h"
#include <iostream>
AudioRecorder::AudioRecorder(QObject *parent) : QObject(parent)
{
}
void AudioRecorder::startRecording()
{
deviceInfo = deviceInfo.defaultInputDevice();
std::cout << deviceInfo.deviceName().toStdString() << std::endl;
format = deviceInfo.preferredFormat();
format.setSampleRate(44100);
format.setChannelCount(1);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
if (!deviceInfo.isFormatSupported(format)) {
std::cout << "raw audio format not supported by backend, finding closest alternative." << std::endl;
format = deviceInfo.nearestFormat(format);
}
audioInput = new QAudioInput(deviceInfo, format, this);
iodevice = audioInput->start();
QObject::connect(AudioRecorder::iodevice, &QIODevice::readyRead, this, &AudioRecorder::onReadyRead);
}
void AudioRecorder::onReadyRead()
{
QByteArray buffer;
auto bytesReady = audioInput->bytesReady();
std::cout << "bytesReady: " << bytesReady << std::endl;
buffer.resize(bytesReady);
//buffer.fill(0);
auto ret = iodevice->read(buffer.data(), bytesReady);
std::cout << "bytes read: " << ret << std::endl;
}
I uploaded the complete project code here: https://www.sendspace.com/file/99dlei

How can I use Qt for creating bluetooth applications?

I'm new to Qt framework. This is my first C++ implementation in real world applications. I was facing problem in preparing this bluetooth based application. I went through Qt documentation too, but it didn't work. Code is :
CLASS HEADER
#ifndef MAINCLASS_H
#define MAINCLASS_H
#include <QObject>
#include <QBluetoothServiceDiscoveryAgent>
#include <QBluetoothServiceInfo>
#include <QBluetoothLocalDevice>
class MainClass : public QObject
{
Q_OBJECT
public:
explicit MainClass(QObject *parent = 0);
~MainClass();
void startDiscovery(void);
signals:
public slots:
void onDiscovery(const QBluetoothServiceInfo &serviceInfo);
private:
QBluetoothServiceDiscoveryAgent *discoveryAgent;
QBluetoothLocalDevice *bluetoothDevice;
};
#endif // MAINCLASS_H
// MEMBER DEFINITIONS
#include "mainclass.h"
#include <QDebug>
MainClass::MainClass(QObject *parent) : QObject(parent)
{
bluetoothDevice = new QBluetoothLocalDevice();
QBluetoothAddress bluetoothAddress = bluetoothDevice->address();
discoveryAgent = new QBluetoothServiceDiscoveryAgent(bluetoothAddress);
connect(discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)),
this, SLOT(onDiscovery(QBluetoothServiceInfo)));
discoveryAgent->setUuidFilter(QBluetoothUuid(QBluetoothUuid::ObexObjectPush));
discoveryAgent->start();
if(!discoveryAgent->isActive())
qDebug()<<"Not active";
if(discoveryAgent->error() != QBluetoothServiceDiscoveryAgent::NoError)
qDebug()<<discoveryAgent->errorString();
}
MainClass::~MainClass()
{
delete(discoveryAgent);
}
void MainClass::onDiscovery(const QBluetoothServiceInfo &serviceInfo)
{
qDebug() << "Discovered service on"
<< serviceInfo.device().name() << serviceInfo.device().address().toString();
qDebug() << "\tService name:" << serviceInfo.serviceName();
qDebug() << "\tDescription:"
<< serviceInfo.attribute(QBluetoothServiceInfo::ServiceDescription).toString();
qDebug() << "\tProvider:"
<< serviceInfo.attribute(QBluetoothServiceInfo::ServiceProvider).toString();
qDebug() << "\tL2CAP protocol service multiplexer:"
<< serviceInfo.protocolServiceMultiplexer();
qDebug() << "\tRFCOMM server channel:" << serviceInfo.serverChannel();
}
Main Function
#include "mainclass.h"
int main()
{
MainClass obj;
}
This piece of code wasn't showing lists of surrounding bluetooth devices. Any suggestions?

How to manipulate multiple Folders/Dir in QT?

I want to know how to manipulate directories until I get video files.
Firstly the main Directory is "F:/TestingVideos/"
Inside the test video there are files e.g:1. Cash Office ,2.Rosville Gate ,3. My Videos
Each of this videos holds other folders for example Cash Office has a Directory of "F:/TestingVideos/Cash Office/" inside we have folders that have dates for example we have the following "F:/TestingVideos/Cash Office/20141201/" Inside the Date Folder I have videos that I want to play.
So far I have implemented a method:
void Dialog::on_loadedButton_clicked(){
QString videoname = "F:/TestingVideos/";`
ui->DirectoryLineEdit->setText(videoName);
QDir dir(videoName);
QFileInfoList files = dir.entryInfoList();
QStringList MonTypeFolder = dir.entryList(QDir::NoDotAndDotDot | QDir::AllDirs, QDir::DirsFirst);
ui->MonitoringcomboBox->addItems( MonTypeFolder);
ui->MonitoringcomboBox->show();
foreach(QFileInfo file, files){
if(file.isDir()){
//qDebug() << "DIR: " << file.fileName();
// qDebug() << "Directory path file:" << file.absoluteFilePath();
QString filePathString = file.absoluteFilePath();
QFileInfo info = QFileInfo(filePathString);
qDebug() << "Folders" << " are writable: " << info.isWritable() << "are readable: " << info.isReadable();
}
if(file.isFile()){
qDebug() << "FILE: " << file.fileName();
}
}
my output is true for my QFileInfo info; for writeable and readable, also I do did a qDebug()<< info.absoluteFilePath() I got the following results:
"F:/TestingVideos"
"F:/"
"F:/TestingVideos/Cash Office"
"F:/TestingVideos/Rosville"
"F:/TestingVideos/My Videos"
I want a way to manipulate the baseNames i.e. Cash Office, Rosville etc... Folders such that I can display their folders e.g. 20141201 in another combobox, since currently ui.monitoringcomboBox->show() can display the base names. I want to be able to manipulate the folders basically To a level where I where I can play a video using QUrl for example.
If i understood correctly you want something like this:
My code is a bit rough but you can use it as starting point:
-MainWindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QComboBox>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QComboBox *mainCB_;
QComboBox *baseCB_;
QComboBox *datesCB_;
QComboBox *mediaCB_;
QString path_;
QStringList media_;
void createComboBoxes();
private slots:
void onBaseComboBoxActivated(QString folderText);
void onDatesComboBoxActivated(QString folderText);
void onMediaComboBoxActivated(QString folderText);
};
#endif // MAINWINDOW_H
-MainWindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QDebug>
#define CBWidth 140
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
media_()
{
ui->setupUi(this);
setFixedSize(840, 400);
path_ = "/Users/its/Desktop/Testing Videos"; //insert your root folder path here
media_ << "*.3gp" << "*.avi" << "*.m4v" << "*.mov" << "*.mp4" << "*.mpeg" << "*.mpg" << "*.3g2" << "*.mxf" << "*.swf" << "*.m2v" << "*.wmv" << "*.flv" << "*.mkv";
QDir dir(path_);
if(dir.exists())
{
createComboBoxes();
}
else
{
qDebug() << "Error: Main dir " << path_ << " doesn't exist.";
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::createComboBoxes()
{
mainCB_ = new QComboBox(this);
mainCB_->addItem(path_.section('/', -1));
mainCB_->setFixedWidth(CBWidth);
mainCB_->move(50, 50);
baseCB_ = new QComboBox(this);
baseCB_->setFixedWidth(CBWidth);
baseCB_->move(250, 50);
datesCB_ = new QComboBox(this);
datesCB_->setFixedWidth(CBWidth);
datesCB_->move(450, 50);
mediaCB_ = new QComboBox(this);
mediaCB_->setFixedWidth(CBWidth);
mediaCB_->move(650, 50);
QDir mainFolderDir(path_);
QStringList mainFolderContent = mainFolderDir.entryList(QDir::NoDotAndDotDot | QDir::AllDirs, QDir::DirsFirst);
baseCB_->addItems(mainFolderContent);
connect(baseCB_, SIGNAL(activated(QString)), this, SLOT(onBaseComboBoxActivated(QString)));
onBaseComboBoxActivated(baseCB_->itemText(0));
connect(datesCB_, SIGNAL(activated(QString)), this, SLOT(onDatesComboBoxActivated(QString)));
connect(mediaCB_, SIGNAL(activated(QString)), this, SLOT(onMediaComboBoxActivated(QString)));
}
void MainWindow::onBaseComboBoxActivated(QString folderText)
{
QDir baseFolderDir(path_ + "/" + folderText);
if(baseFolderDir.exists())
{
QStringList baseFolderContent = baseFolderDir.entryList(QDir::NoDotAndDotDot | QDir::AllDirs, QDir::DirsFirst);
datesCB_->clear();
datesCB_->addItems(baseFolderContent);
onDatesComboBoxActivated(datesCB_->itemText(0));
}
else
{
qDebug() << "Error: Base dir " << path_ + "/" + folderText << " doesn't exist.";
}
}
void MainWindow::onDatesComboBoxActivated(QString datesText)
{
QDir datesFolderDir(path_ + "/" + baseCB_->currentText() + "/" + datesText);
if(datesFolderDir.exists())
{
QStringList datesFolderContent = datesFolderDir.entryList(media_, QDir::Files, QDir::Name);
mediaCB_->clear();
mediaCB_->addItems(datesFolderContent);
onMediaComboBoxActivated(mediaCB_->itemText(0));
}
else
{
qDebug() << "Error: Dates dir " << path_ + "/" + baseCB_->currentText() + "/" + datesText << " doesn't exist.";
}
}
void MainWindow::onMediaComboBoxActivated(QString mediaText)
{
qDebug() << "Media selected with URL:" << path_ + "/" + baseCB_->currentText() + "/" + datesCB_->currentText() + "/" + mediaText;
}
I hope this will help you.

udp packet is not received in QThread

I'm trying to receive some packets using a udpReceiver class that I have written using qUdpSocket in a separate QThread :
class udpThread : public QThread
{
private:
QObject * parent;
public:
udpThread(QObject * parent = 0)
{
this->parent = parent;
}
void run()
{
UdpReceiver * test = new UdpReceiver(parent);
}
};
class UdpReceiver : public QObject
{
Q_OBJECT
private:
QUdpSocket * S;
int port;
public:
UdpReceiver(QObject* parent = 0) : QObject(parent)
{
port = 9003;
initialize();
}
UdpReceiver(int p,QObject* parent = 0) : QObject(parent)
{
port = p;
initialize();
}
void initialize()
{
S = new QUdpSocket();
S->bind(port);
S->connect(S,SIGNAL(readyRead()),this,SLOT(readPendingDiagrams()));
qDebug() << "Waiting for UDP data from port " << port << " ... \n";
}
public slots:
void readPendingDiagrams()
{
while(S->waitForReadyRead())
{
QByteArray datagram;
datagram.resize(S->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
S->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
qDebug() << datagram.size() << " bytes received .... \n";
qDebug() << " bytes received .... \n";
}
}
};
And here is the main() method :
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// UdpReceiver * net = new UdpReceiver();
MainWindow w;
udpThread * ut = new udpThread();
ut->start();
w.show();
return a.exec();
}
Now when I use the udpReceiver class to get the packets without the QThread it works just fine, but when I use the udpThread class it doesn't get the packets or at least the raedyread() signal does not activate some how.
When I try to get the packets without the QThread my GUI crashes somehow and the whole program hangs, that's why I want to use QThread.
I appreciate if you could help me solve this :)
Regards,
You've fallen into the same trap as many do when working with threads in Qt: http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/.
It is almost always a bad idea to subclass QThread (see http://woboq.com/blog/qthread-you-were-not-doing-so-wrong.html for counterexamples).
Change your code as follows to do it the "intended" way (create a new QThread and call moveToThread on your QObject to move it to the new thread). You'll see from the output that the thread the UdpReceiver is created on is not the same as the one it receives data on, which is what you want:
#include <QApplication>
#include <QDebug>
#include <QThread>
#include <QUdpSocket>
class UdpReceiver : public QObject
{
Q_OBJECT
private:
QUdpSocket * S;
int port;
public:
UdpReceiver(QObject* parent = 0) : QObject(parent)
{
qDebug() << "Construction thread:" << QThread::currentThreadId();
port = 9003;
initialize();
}
UdpReceiver(int p,QObject* parent = 0) : QObject(parent)
{
port = p;
initialize();
}
void initialize()
{
S = new QUdpSocket();
S->bind(port);
S->connect(S,SIGNAL(readyRead()),this,SLOT(readPendingDiagrams()));
qDebug() << "Waiting for UDP data from port " << port << " ... \n";
}
public slots:
void readPendingDiagrams()
{
qDebug() << "Reading thread:" << QThread::currentThreadId();
while(S->waitForReadyRead())
{
QByteArray datagram;
datagram.resize(S->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
S->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
qDebug() << datagram.size() << " bytes received .... \n";
qDebug() << " bytes received .... \n";
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QThread *t = new QThread();
t->start();
UdpReceiver * net = new UdpReceiver();
net->moveToThread(t);
return a.exec();
}
#include "main.moc"
I don't have your UI code, so I don't know about any issues there. Feel free to post another question if you get stuck there and mention it in a comment and I'll try to help.
Vahid Nateghi, the init codes and the work codes must run in the same thread. But the constructor of UdpReceiver runs in the main thread against the one readPendingDiagrams runs in, that was the bug. Try this:
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QUdpSocket>
class UdpReceiver : public QObject
{
Q_OBJECT
private:
QUdpSocket * S;
int port;
public:
UdpReceiver(QObject* parent = 0) : QObject(parent)
{
qDebug() << ">HERE was the bug! thread:" << QThread::currentThreadId() << "in Construction of UdpReceiver:" << __LINE__ ;
}
public slots:
void init_thread(){
port = 10000;
qDebug() << ">thread:" << QThread::currentThreadId() << "in init_thread:" << __LINE__ ;
S = new QUdpSocket();
S->bind(port);
S->connect(S,SIGNAL(readyRead()),this,SLOT(readPendingDiagrams()));
qDebug() << "Waiting for UDP data from port " << port << " ... \n";
}
void readPendingDiagrams()
{
qDebug() << ">thread:" << QThread::currentThreadId() << "in readPendingDiagrams:" << __LINE__ ;
while(S->waitForReadyRead())
{
QByteArray datagram;
datagram.resize(S->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
S->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
qDebug() << datagram.size() << " bytes received in thread " << QThread::currentThreadId() << "in readPendingDiagrams:" << __LINE__ ;
}
}
};
int main(int argc, char *argv[])
{
qDebug() << ">Main thread:" << QThread::currentThreadId() << "in main:" << __LINE__ ;
QCoreApplication a(argc, argv);
QThread *t = new QThread();
UdpReceiver * net = new UdpReceiver();
net->moveToThread(t);
net->connect(t,SIGNAL(started()),net,SLOT(init_thread()));
t->start();
return a.exec();
}
#include "main.moc"