Block execution program until callback function complete execution - c++

How to block program execution until callback function complete execution ?
From my main() i launch interface.getImage(); function who want to get images from our database. When we receive images the callback function void InterfaceColliseo::dataReceived (std::shared_ptr data) start to execute.
But I have a problem my program main() terminate before my callback function execution ?
main.cpp
int main(){
InterfaceColliseo interface;
IMAGE = true;
interface.getImage();
// want to block program here
return 0;
}
callback function
void InterfaceColliseo::dataReceived (std::shared_ptr<IData> data)
{
if (!data->isValid())
return;
const unsigned char* twoDImageData = data->get2DImageData();
int width2DImageData = data->getWidth2DImageData();
int height2DImageData = data->getHeight2DImageData();
const unsigned char* disparityData = data->getDisparityData();
int widthDisparityData = data->getWidthDisparityData();
int heightDisparityData = data->getHeightDisparityData();
if(IMAGE) {
saveImage(twoDImageData, width2DImageData, height2DImageData,
disparityData, widthDisparityData, heightDisparityData);
IMAGE = false;
}
if(ACQUISATION){
QList<GstObservationBasic> detectorData = data->getObstaclesData();
getObstacles(detectorData);
}
}

I think you just can use thread from std. When you use join, the main thread will wait until joined thread will finish his job.
#include <thread>
//in main
std::thread myThread(interface.getImage);
myThread.join();

#include "interface_colliseo.h"
std::mutex mtx;
std::condition_variable cv;
bool IMAGE;
bool ACQUISATION;
InterfaceColliseo::InterfaceColliseo(){
}
void InterfaceColliseo::startStreaming(){
dataReceiver = _device->getDataReceiver();
start();
}
void InterfaceColliseo::getImage(){
dataReceiver = _device->getDataReceiver();
start();
}
InterfaceColliseo::InterfaceColliseo(QString IP): _IP(IP) {
qDebug() << "INDUS-5: IP server: " << _IP;
qDebug() << "INDUS-5: Connecting to sensor...";
_colliseoClient.setIPServer(_IP);
}
bool InterfaceColliseo::connect2UT(){
QString path = qApp->applicationDirPath()+"/Configuration.ini";
QSettings config(path, QSettings::IniFormat);
_IP = config.value("Connection/IP","10.0.3.144").toString();
_colliseoClient.setIPServer(_IP);
_device = _colliseoClient.getDevice();
_device->connectSensor();
bool connect = _device->isConnected();
return connect;
}
QString InterfaceColliseo::sensorName(){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getOrderNumber();
}
QString InterfaceColliseo::sensorFirmwareVersion(){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getFirmwareVersion();
}
QString InterfaceColliseo::getSensorHeadPN(QString sensor){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getSensorHeadPN(sensor);
}
QString InterfaceColliseo::getEvaluationUnitSN(){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getEvaluationUnitSN();
}
QString InterfaceColliseo::getEvaluationUnitPN(){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getEvaluationUnitPN();
}
QString InterfaceColliseo::getEvaluationUnitFirmwareVersion(){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getEvaluationUnitFirmwareVersion();
}
QString InterfaceColliseo::getEstimatedAngleX(){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getEstimatedAngleX();
}
QString InterfaceColliseo::getEstimatedAngleZ(){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getEstimatedAngleZ();
}
QString InterfaceColliseo::getEstimatedHeight(){
return _device->getDeviceDiagnostics()->getOperatingData()
->getDeviceInformation()->getEstimatedHeight();
}
void InterfaceColliseo::saveImage(const unsigned char*twoDImageData,
int width2DImageData, int height2DImageData,
const unsigned char*disparityData,
int widthDisparityData, int disptHeight){
Configuration configuration;
QString logFolder = configuration.getLogFolder();
QImage imgRight(twoDImageData, width2DImageData, height2DImageData, QImage::Format_Indexed8);
QImage imgDisparity(disparityData, widthDisparityData, disptHeight, QImage::Format_Indexed8);
QPixmap imgRght = QPixmap::fromImage(imgRight);
QPixmap imgDisp = QPixmap::fromImage(imgDisparity);
QString rghtImgPath = logFolder + "raw_image.png";
QString dispImgPath = logFolder + "disp_image.png";
imgRght.save(rghtImgPath, "PNG");
imgDisp.save(dispImgPath, "PNG");
}
void InterfaceColliseo::getObstacles(QList<GstObservationBasic> detectorData){
if (detectorData.size() == 0)
{
qDebug() << "Obstacles: no detected obstacles.";
return;
}
Configuration config;
config.writeLog("***************Obstacles List Acquisation******************");
Q_FOREACH(const GstObservationBasic &obs, detectorData)
{
qDebug() << "Obstacles: " << gstObservationToString(obs);
config.writeLog(gstObservationToString(obs));
}
}
void InterfaceColliseo::dataReceived (std::shared_ptr<IData> data)
{
if (!data->isValid())
return;
const unsigned char* twoDImageData = data->get2DImageData();
int width2DImageData = data->getWidth2DImageData();
int height2DImageData = data->getHeight2DImageData();
const unsigned char* disparityData = data->getDisparityData();
int widthDisparityData = data->getWidthDisparityData();
int heightDisparityData = data->getHeightDisparityData();
if(IMAGE) {
saveImage(twoDImageData, width2DImageData, height2DImageData,
disparityData, widthDisparityData, heightDisparityData);
IMAGE = false;
}
if(ACQUISATION){
QList<GstObservationBasic> detectorData = data->getObstaclesData();
getObstacles(detectorData);
ACQUISATION = false;
}
}
void InterfaceColliseo::start() {
dataReceiver->addListener(this);
if(dataReceiver->isListening())
dataReceiver->stopListening();
dataReceiver->startListening();
_device->triggerSingleImageAcquisition();
}

Related

Receiving fatal error assigning QSharedPointer in QtTest

In TestGroup_Person, when I retrieve a QSharedPointer<-JB_TableRowProt> from JB_PersonDao and assign it to QSharedPointer<-JB_TableRowProt> aGroup_Person (in .h), I then get this error in the methods of TestGroup_Person.
Alternatively, if I retrieve a QSharedPointer<-JB_TableRowProt> from JB_DaoProt in each method (and don't assign it to QSharedPointer<-JB_TableRowProt> aGroup_Person), it works fine.
Can someone explain to me why this assignment appears to be causing the error please?
I got this error:
QFATAL : TestGroup_Person::test_getDBTable_Name() Received signal 11
Function time: 0ms Total time: 0ms
FAIL! : TestGroup_Person::test_getDBTable_Name() Received a fatal error.
Here's the code:
main:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList arguments = QCoreApplication::arguments();
QFile aFile(DATABASE_FILENAME); // remove existing SP3.db
if (aFile.exists())
aFile.remove();
map<QString, unique_ptr<QObject>> tests;
tests.emplace("group_person", make_unique<TestGroup_Person>());
if (arguments.size() >= 3 && arguments[1] == "-select") {
QString testName = arguments[2];
auto iter = tests.begin();
while(iter != tests.end()) {
if (iter->first != testName) {
iter = tests.erase(iter);
} else {
++iter;
}
}
arguments.removeOne("-select");
arguments.removeOne(testName);
}
int status = 0;
for(auto& test : tests) {
status |= QTest::qExec(test.second.get(), arguments);
}
return status;
}
TestGroup_Person.h
#include <QString>
#include <QtTest>
#include <QSharedPointer>
#include "A_DB_Classes/JB_DatabaseManager.h"
#include "A_Tables/JB_Group_Person.h"
class TestGroup_Person : public QObject
{
Q_OBJECT
public:
TestGroup_Person();
private Q_SLOTS:
void test_allFieldsEqualsFieldNames();
void test_getDBTable_FieldNames();
void test_getDBTable_Name();
void test_hasJoinTable();
void test_setValueForField();
void test_setStorageValueForField();
void test_getStorageFields();
private:
JB_DatabaseManager& mDB;
QSharedPointer<JB_TableRowProt> aGroup_Person;
};
TestGroup_Person.cpp:
TestGroup_Person::TestGroup_Person():
mDB(JB_DatabaseManager::instance())
{
aGroup_Person = mDB.aPersonDao.getJoinTableObject();
}
void TestGroup_Person::test_allFieldsEqualsFieldNames()
{
const QVector<QString>& aVector = aGroup_Person->getDBTable_FieldNames();
const QList<QString> aList = aGroup_Person->getAllFieldNames();
bool isThere = true;
QString fieldName = "";
QString aResult = "This field name does not exist in all_FieldNamesAndValuesH";
for (int i = 0; i < aVector.size() && isThere; ++i) {
fieldName = aVector.at(i);
isThere = aList.contains(aVector.at(i));
}
if (isThere)
aResult = fieldName;
QCOMPARE(fieldName, QString(aResult));
}
void TestGroup_Person::test_getDBTable_FieldNames()
{
const QVector<QString>& aVector = aGroup_Person->getDBTable_FieldNames();
QString fieldName = "";
for (int i = 0; i < aVector.size(); ++i) {
fieldName = fieldName + aVector.at(i) +",";
}
QVector<QString> fieldNames;
QVector<QString> columnHeadings;
aGroup_Person->getViewableFieldNamesAndHeadings(fieldNames, columnHeadings);
bool correct = fieldNames.count() == columnHeadings.count();
if (!correct)
correct = columnHeadings.count() == 0;
QCOMPARE(correct, true);
QCOMPARE(fieldName, QString("groupID,personID,jobID,grp_per_dateTimeStamp,"));
}
void TestGroup_Person::test_getDBTable_Name()
{
QCOMPARE(aGroup_Person->getDBTable_Name(), QString("Group_Person"));
}
Relevant method of JB_DaoProt:
QSharedPointer<JB_TableRowProt> JB_DaoProt::getJoinTableObject()
{
JB_TableRowProt* aJoinTable = new_JoinTableRowProt();
QSharedPointer<JB_TableRowProt> pJoinTable(aJoinTable);
return pJoinTable;
}

Prevent qDebug() from writing to std output

I am using qDebug(), qInfo() and so on in combination of qInstallMessageHandler to write my logfiles. I also get an output on my batch screen, when executing my application.
I only found QT_NO_DEBUG_OUTPUT, but I want to toggle this configuration while run-time. Is there a way to prevent Qt from writing to std output?
sadly no, you only get access to the messages, but cannot prevent from beeing written to std output.
That's false in Qt 5 at the very least. The message printing code looks as follows: you can clearly see that only the message handler is being used:
if (grabMessageHandler()) {
// prefer new message handler over the old one
if (msgHandler.load() == qDefaultMsgHandler
|| messageHandler.load() != qDefaultMessageHandler) {
(*messageHandler.load())(msgType, context, message);
} else {
(*msgHandler.load())(msgType, message.toLocal8Bit().constData());
}
ungrabMessageHandler();
} else {
fprintf(stderr, "%s\n", message.toLocal8Bit().constData());
}
As you can see, the fprintf(stderr, ...) is a fallback only if recursion is detected from within the messageHandler itself.
Thus, all you need to prevent any debug output is to implement and set your own messageHandler.
To completely turn off all the debug output in Qt, the following works:
#include <QtCore>
int main() {
qDebug() << "I'm not quiet at all yet";
qInstallMessageHandler(+[](QtMsgType, const QMessageLogContext &, const QString &){});
qDebug() << "I'm very, very quiet";
}
In any case, a sensible implementation of an application-wide file logger might look as follows - it doesn't recreate the QTextStream unnecessarily; it uses QString::toUtf8() instead, and explicitly writes line endings.
#include <QtCore>
class Logger {
static struct Data {
Logger *instance;
QtMessageHandler chainedHandler;
} d;
bool m_isOpen;
QFile m_logFile;
QtMessageHandler m_oldHandler = {};
static void handler(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
if (d.instance)
d.instance->log(msg);
if (d.chainedHandler)
d.chainedHandler(type, context, msg);
}
public:
enum ChainMode { DontChain, Chain };
Logger() {
Q_ASSERT(!instance());
m_logFile.setFileName("myLog.txt");
m_isOpen = m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
d.instance = this;
}
~Logger() { uninstallHandler(); }
bool isOpen() const { return m_isOpen; }
void installHandler(ChainMode mode) {
Q_ASSERT(!m_oldHandler);
m_oldHandler = qInstallMessageHandler(handler);
if (mode == Chain)
d.chainedHandler = m_oldHandler;
}
void uninstallHandler() {
if (m_oldHandler) {
m_oldHandler = nullptr;
d.chainedHandler = nullptr;
qInstallMessageHandler(m_oldHandler);
}
}
/// This method is *not* thread-safe. Use with a thread-safe wrapper such as `qDebug`.
void log(const QString & msg) {
if (isOpen()) {
m_logFile.write(msg.toUtf8());
m_logFile.write("\n", 1);
}
}
/// Closes the log file early - this is mostly used for testing.
void endLog() {
uninstallHandler();
m_logFile.close();
}
static Logger *instance() { return d.instance; }
};
Logger::Data Logger::d;
template <typename T> QByteArray streamOutputFor(const T &data) {
QBuffer buf;
buf.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream s(&buf);
s << data << endl;
buf.close();
return buf.data();
}
QByteArray readEnd(const QString &fileName, int count) {
QFile file(fileName);
if (file.open(QIODevice::ReadOnly | QIODevice::Text) && file.size() >= count) {
file.seek(file.size() - count);
return file.readAll();
}
return {};
}
void test() {
auto const entry = QDateTime::currentDateTime().toString().toUtf8();
Q_ASSERT(Logger::instance()->isOpen());
qDebug() << entry.data();
Logger::instance()->endLog();
auto reference = streamOutputFor(entry.data());
auto readback = readEnd("myLog.txt", reference.size());
Q_ASSERT(!reference.isEmpty());
Q_ASSERT(readback == reference);
}
int main() {
Logger logger;
logger.installHandler(Logger::DontChain);
qDebug() << "Something or else";
test();
}

Poco TCPServer does not start outside main

When i do the initialisation of the TCPServer inside of main it works, when i try to start it with the startServer() function it is not working, i mean i can not establish a connection with putty.
What am i doing wrong here?
Thanks for any help.
class EchoConnection : public TCPServerConnection {
public:
EchoConnection(const StreamSocket& s)
: TCPServerConnection(s) {}
void reply(char buffer[])
{
bzero(buffer, 256);
std::string myWord = "myWord\n\r";
strcpy(buffer, myWord.c_str());
}
void run() {
StreamSocket& ss = socket();
try {
char buffer[256];
int n = ss.receiveBytes(buffer, sizeof(buffer));
while (n > 0) {
reply(buffer);
ss.sendBytes(buffer, sizeof(buffer));
n = ss.receiveBytes(buffer, sizeof(buffer));
}
}
catch (Poco::Exception& exc)
{ std::cerr << "EchoConnection: " << exc.displayText() << std::endl; }
}
};
void startServer()
{
Poco::Net::TCPServer srv(new Poco::Net::TCPServerConnectionFactoryImpl<EchoConnection>, 8089);
srv.start();
SocketAddress sa("localhost", srv.socket().address().port());
StreamSocket ss(sa);
std::string data("hello, world");
ss.sendBytes(data.data(), (int)data.size());
char buffer[256] = { 0 };
int n = ss.receiveBytes(buffer, sizeof(buffer));
std::cout << std::string(buffer, n) << std::endl;
}
int main(int argc, char** argv) {
Poco::Net::TCPServer srv(new Poco::Net::TCPServerConnectionFactoryImpl<EchoConnection>, 8089);
srv.start();
SocketAddress sa("localhost", srv.socket().address().port());
StreamSocket ss(sa);
std::string data("hello, world");
ss.sendBytes(data.data(), (int)data.size());
char buffer[256] = { 0 };
int n = ss.receiveBytes(buffer, sizeof(buffer));
std::cout << std::string(buffer, n) << std::endl;
// startServer(8089);
ModuleData modData;
modData.ModuleNumber = 1;
modData.ModuleTypeId = 1;
string test = modData.serialize();
ifstream dataFile;
dataFile.open("ModuleData.dat");
if (dataFile.is_open())
{
string line;
while (getline(dataFile, line))
{
cout << line << std::endl;
}
dataFile.close();
}
while (1)
{
}
srv.stop();
}
At the end of startServer function srv object is deleted. TCPServer uses own thread but it finishes working in destructor of TCPServer.
Look at implementation of ~TCPServer
TCPServer::~TCPServer() {
try {
stop();
_pDispatcher->release();
...
}
and see stop method implementation
void TCPServer::stop() {
if (!_stopped)
{
_stopped = true; // !!
_thread.join(); // waiting for thread
_pDispatcher->stop();
}
}
the body of thread function is in run method
void TCPServer::run()
{
while (!_stopped) // this flag was set by stop method
{
... // body of thread function
}
}
stop method sets _stopped on true, and for this reason thread finishes working.

How to delete boost io_service

My simplified question
I read this thread and I am trying to delete the io_service object. I do this
m_IO.stop();
m_IO.~io_service();
m_IO is an object of boost::asio::io_service. I found that my thread was blocked by m_IO.~io_service(); How can I delete io_service?
My Complete question
I am making a daily timer by using boost io_service and deadline timer. The problem is when I want to delete my daily timer, my thread will disappear when it try to delete boost io_service.
main.cpp
int main()
{
myDailyTimer* pTimer = new myDailyTimer;
// do something
delete pTimer;
return 0;
}
I set break points in myDailyTimer.cpp::int i = 0; and myDailyTimer.cpp::int j = 0; and main::return 0; My main thread can reach int i = 0;, My timer thread cannot reach int j = 0;, My main thread cannot reach return 0;.
I found the my main thread will disappear when it try to delete boost::asio::io_service object. How to solve this problem? Am I using boost::asio::io_service in a wrong way?
myDailyTimer.h
class myDailyTimerInterface
{
public:
myDailyTimerInterface(){}
~myDailyTimerInterface(){}
virtual void TimerCallback(int nTimerID) = 0;
};
class myDailyTimer :
public myThread
{
public:
boost::asio::io_service m_IO;
boost::asio::deadline_timer * m_pTimer;
tm m_tmSpecificTime;
std::string m_strSpecificTime;
int m_nTimerID;
myDailyTimerInterface* m_pParent;
public:
myDailyTimer();
~myDailyTimer();
void SetTime(tm strIN, int nID); // msec
void TimerCallback();
//Override
void ThreadMain();
protected:
std::string MakeStringSpecificTime();
void AddOneDay();
};
myDailyTimer.cpp
myDailyTimer::myDailyTimer()
{
m_pTimer = 0;
m_strSpecificTime = "";
}
myDailyTimer::~myDailyTimer()
{
EndThread();
if (m_pTimer != 0)
{
m_pTimer->cancel();
delete m_pTimer;
}
m_IO.stop();
m_IO.~io_service();
int i = 0;
i++;
}
void myDailyTimer::SetTime(tm tmIN, int nID) // msec
{
if (m_pTimer != 0)
{
m_pTimer->cancel();
delete m_pTimer;
}
m_tmSpecificTime = tmIN;
m_strSpecificTime = MakeStringSpecificTime();
m_nTimerID = nID;
m_pTimer = new boost::asio::deadline_timer(m_IO, boost::posix_time::time_from_string(m_strSpecificTime));
m_pTimer->async_wait(boost::bind(&myDailyTimer::TimerCallback, this));
myThread::Start();
}
std::string myDailyTimer::MakeStringSpecificTime()
{
time_t localTime;
localTime = mktime(&m_tmSpecificTime); // time is GMT local
struct tm * ptm = gmtime(&localTime); // convert time to GMT +0
char veccNextTime[64];
memset(veccNextTime, 0, sizeof(veccNextTime));
sprintf(veccNextTime, "%d-%02d-%02d %02d:%02d:%02d.000",
ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday,
ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
std::string strTemp(veccNextTime);
return strTemp;
}
void myDailyTimer::AddOneDay()
{
m_tmSpecificTime.tm_mday += 1;
mktime(&m_tmSpecificTime); /* normalize result */
}
void myDailyTimer::TimerCallback()
{
if (m_pParent != 0)
m_pParent->TimerCallback(m_nTimerID);
//m_timer->expires_from_now(boost::posix_time::milliseconds(m_nTimerDuration));
AddOneDay();
m_strSpecificTime = MakeStringSpecificTime();
m_pTimer->expires_at(boost::posix_time::time_from_string(m_strSpecificTime));
m_pTimer->async_wait(boost::bind(&myDailyTimer::TimerCallback, this));
}
//Override
void myDailyTimer::ThreadMain()
{
while (!IsEndThread())
m_IO.run();
int j = 0;
j++;
}
As Dan MaĊĦek mentioned, explicitly calling the destructor isn't a good pattern here. The standard way to stop an io_service is to stop every "work" that is pending and then wait for io_service::run function to return. Also, to prevent the io_service::run function from returning prematurely, it is a good idea to create an instance of io_service::work object.
Hope you'll be able to modify this example to your use case:
namespace asio = boost::asio;
class MyTimer {
using Clock = std::chrono::steady_clock;
public:
MyTimer(Clock::duration duration)
: _work(_ios)
, _timer(_ios)
, _thread([this] { _ios.run(); })
{
_ios.post([this, duration] { start(duration); });
}
~MyTimer() {
_ios.post([this] { stop(); });
_thread.join();
}
private:
void start(Clock::duration duration) {
_timer.expires_from_now(duration);
_timer.async_wait([this](boost::system::error_code) {
// NOTE: Be careful here as this is run from inside
// the thread.
if (!_work) {
// Already stopped.
std::cout << "Stopped" << std::endl;
return;
}
std::cout << "Timer fired" << std::endl;
});
}
void stop() {
_work.reset();
_timer.cancel();
}
private:
asio::io_service _ios;
boost::optional<asio::io_service::work> _work;
asio::steady_timer _timer;
std::thread _thread;
};
int main() {
auto* my_timer = new MyTimer(std::chrono::seconds(1));
delete my_timer;
return 0;
}

Custom class to XML using QSettings

I'd like to save custom class to XML using QSettings. But I always get XML without structure members.
#include <QCoreApplication>
#include <QtCore/qdatastream.h>
#include <qxmlstream.h>
#include <qdebug.h>
#include <QtCore/QSettings>
#include <QMetaType>
struct Interface_struct
{
QString name;
QString ip;
};
Q_DECLARE_METATYPE(Interface_struct)
QDataStream& operator <<(QDataStream& out, const Interface_struct& s)
{
out << s.name << s.ip;
return out;
}
QDataStream& operator >>(QDataStream& in, Interface_struct& s)
{
in >> s.name;
in >> s.ip;
return in;
}
static bool readXmlFile(QIODevice &device, QSettings::SettingsMap &map)
{
qDebug()<< "read";
QXmlStreamReader reader(&device);
QString key;
while(!reader.atEnd())
{
reader.readNext();
if( reader.isStartElement() && reader.tokenString() != "Settings")
{
if( reader.text().isNull() )
{
// key = Settings
if(key.isEmpty())
{
key = reader.tokenString();
}
// key = Settings/Intervall
else
{
key += "/" + reader.tokenString();
}
}
else
{
map.insert(key, reader.text().data());
}
}
}
return true;
}
static bool writeXmlFile(QIODevice &device, const QSettings::SettingsMap &map)
{
qDebug()<< "write";
QXmlStreamWriter writer(&device);
writer.writeStartDocument("1.0");
writer.writeStartElement("Settings");
foreach(QString key, map.keys())
{
foreach(QString elementKey, key.split("/"))
{
writer.writeStartElement(elementKey);
}
writer.writeCharacters(map.value(key).toString());
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndDocument();
return true;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qRegisterMetaType<Interface_struct>("Interface_struct");
qRegisterMetaTypeStreamOperators<Interface_struct>("Interface_struct");
{
Interface_struct s;
s.name = QString("br03000");
s.ip = QString("172.16.222.5");
const QSettings::Format xml_format =
QSettings::registerFormat("xml", readXmlFile, writeXmlFile);
if(xml_format == QSettings::InvalidFormat)
{
qDebug() << "InvalidFormat!";
return 0;
}
QSettings::setPath(xml_format, QSettings::UserScope, "/home/farit/test/");
QSettings settings(xml_format, QSettings::UserScope, "xml_cfg");
settings.setValue("network", QVariant::fromValue(s));
}
{
QSettings::Format xml_format =
QSettings::registerFormat("xml", readXmlFile, writeXmlFile);
QSettings::setPath(xml_format, QSettings::UserScope, "/home/farit/test/");
QSettings settings(xml_format, QSettings::UserScope, "xml_cfg");
QVariant value = settings.value("network");
Interface_struct interface = value.value<Interface_struct>();
qDebug() << "TEST: " << interface.name << interface.ip;
}
return 0;
}
I get this output:
read
write
read
TEST: "" ""
Press <RETURN> to close this window...
And XML looks like this:
<?xml version="1.0" encoding="UTF-8"?><Settings><network></network></Settings>
How can I save structure members of custom class to XML using QSettings?
UPDATE: I'm sorry, I forgot to mention, that is supposed to be done in Qt4.