Calling a method from a different .cpp file - qt

I want to save some data as a text file, the first txt file will contain header information, the other text file will save data streamed from sensors, so with the help from the internet I created the following "datalogger.cpp" file
#include "datalogger.h"
#include <QDebug>
#include <iostream>
#include <QFile>
DataLogger::DataLogger(QObject *parent) : QObject(parent)
{
}
DataLogger::~DataLogger(){
}
void DataLogger::save(DataStream &input){
saveAsText(input);
}
void DataLogger::saveAsText(DataStream &input){
QTextStream outHeader(&outFileHeader);
outHeader << "[CAPTURE SETTINGS]\n"
<< "Filename: " << SettingsSingleton::instance().getFileName() << ".txt \n"
<< "Samples: " << QString::number(input.size()) << "\n"
<< "Duration: " << QString::number(input.back().time) << "ms \n"
<< "Sample rate: " << QString::number(SettingsSingleton::instance().getSampleRate()) << " Hz\n"
<< "Source: " << SettingsSingleton::instance().getSource() << "\n"
outFileHeader.close();
}
QFile outFile(SettingsSingleton::instance().getFileName() + ".txt");
QTextStream out(&outFile);
for (int i ; i<input.size();i++){
const EcgStreamObject tmp=input.at(i);
out << tmp.toText() << endl; //"\n";
}
outFile.close();
}
}
I have my "DataStream" input variable that I want to pass to the method and save as a ".txt" file, however I do no know how to call the method "void DataLogger::save(DataStream &input)" from a different ".cpp" file where the DataStream variable is located.
I am extremely new to c++ please it as simple as possible please.
Thank you in advance

If I get your question right, it is about how to create and use a header file in c++.
There is already a lot of information about this, for example this article from cplusplus.com or this from learncpp.com.

All you should need to do is add "datalogger.h" to your other file.
When you call the method DataLogger::save from your other file, the program will search for an implementation that was linked to your program (i.e. the file you posted here) and use that to actually perform the work.
Stefan's answer is probably important to look at too as it will cover this case and some other basics if you are going to be working in C/C++ long term.

Related

Reading Rich Text Character and Block Formatting

I have rich text items implemented using QGraphicsTextItem
To set font size, for example:
void set (int fontSize) {
QTextCursor _cursor = textCursor();
QTextCharFormat _format;
_format.setFontPointSize(fontSize);
_cursor.mergeCharFormat(_format);
setTextCursor(_cursor); }
A lot more complicated is to read the font size.
Assuming I have a selection, I must iterate through the document, through all QTextBlock, QTextFragment, reading the QTextCharFormat ...
But the simple option, if there is no selection, just reading the font size at cursor:
int get () {
return textCursor().charFormat().fontPointSize(); }
This works, but I found 3 issues:
1) Setting font size by QGraphicsTextItem properties:
QFont f = font();
f.setPointSize(20);
setFont(f);
this returns 0 by my get function above. To set the font size for the entire item, I have to use the same method as in the set function.
Shouldn't the setFont method set a font that can be read from the QTextCursor ?
2) setHtml can set formatting - but I don't see any way to read that formatting
How can I read the rich text formatting from an html fragment ? Is the only posiblity, parsing the html ?
3) (my current stumbling block)
Copy formatted text from an outside source and paste in the QGraphicsTextItem seems to maintain the formatting of the source - but how can I read that formatting ?
The get method above reads font size 0 if the text was pasted from outside.
font().pointSize() always returns 8. (I have not set it so I imagine that is a default)
Is there another method to read the text format ?
is the clipboard text formatted using html ?
How can I find the font size (or any other formatting) from the pasted text ?
(The same questions apply to block formatting, like alignment).
I think most of your problems could be solved by getting the QTextDocument for your QGraphicsTextItem object and work with it. QTextDocument and its methods (like QTextFormat::property(int propertyId)) can help you to get a lot of properties for your text.
1) If you set the size using the QFont object, you should get the size using the same way.
2) When you set the text using html, QGraphicsTextItem::font() is not useful so you need to get the QTextDocument and use their functions instead.
3) Same as 2. I think... because I don't have your code to test it :)
Well, here you have a code as an example. I hope this answer helps you.
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsTextItem>
#include <QTextCursor>
#include <QTextCharFormat>
#include <QFont>
#include <QDebug>
#include <QTextDocument>
#include <QTextBlock>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
/* ITEM 1 */
QGraphicsTextItem* item_1 = new QGraphicsTextItem("QGraphicsTextItem 1");
item_1->setTextInteractionFlags(Qt::TextEditorInteraction);
QFont f = item_1->font();
f.setPointSize(30);
item_1->setFont(f);
qDebug() << "textCursor().position() (returns 0): " <<
item_1->textCursor().position();
qDebug() << "textCursor().charFormat().fontPointSize() (returns 0): " <<
item_1->textCursor().charFormat().fontPointSize();
qDebug() << "font().pointSize() (returns 30 - OK!): " <<
item_1->font().pointSize();
QTextDocument* doc = item_1->document();
f = doc->defaultFont();
qDebug() << "pointSize (returns 30 - OK!): " << f.pointSize();
scene.addItem(item_1);
/* ITEM 2 */
QGraphicsTextItem* item_2 = new QGraphicsTextItem();
item_2->setPos(0, 50);
item_2->setHtml("<html><head/><body><p>"
"<span style=\"font-size:14pt; font-weight:600;\">QGraphics</span>"
"<span style=\"font-size:24pt; font-weight:600;\">TextItem 2</span>"
"</p></body></html>");
qDebug() << "font().pointSize() (returns 8, the default value): "
<< item_2->font().pointSize();
doc = item_2->document();
f = doc->defaultFont();
qDebug() << "pointSize (returns 8, the default value): " << f.pointSize();
QVector<QTextFormat> formats = doc->allFormats();
QVectorIterator<QTextFormat> i(formats);
while (i.hasNext()) {
QTextFormat format = i.next();
if (format.property(QTextFormat::FontPointSize).isValid())
qDebug() << "format.property (returns 14 or 24): " <<
format.property(QTextFormat::FontPointSize).toInt();
}
/*
* Get the block of text. In this example, we only have one block, but
* two text fragments (see below)
*/
QTextBlock text_block = item_2->document()->findBlock(1);
QTextBlock::iterator it;
for (it = text_block.begin(); !(it.atEnd()); ++it) {
QTextFragment currentFragment = it.fragment();
if (currentFragment.isValid())
qDebug() << "currentFragment.text(): " << currentFragment.text();
qDebug() << "currentFragment.charFormat().font().pointSize() "
"(returns 14 or 24, depending on"
"the current text fragment): " <<
currentFragment.charFormat().font().pointSize();
}
scene.addItem(item_2);
view.setFixedSize(640, 480);
view.show();
return a.exec();
}

Reading more than one value into variables using QInputDialog

I have to write a small QT program that reads in 3 mark percentages separated by commas and then do some further calculations on the marks... I have to use QInputDialog to do this but it seems like it's only possible to read in one value at a time.
at this stage I am only trying to read in and display the three marks.
When I run this code QTCreator stops working and I have to end the process in task manager.
Any idea how I can approach this would be much appreciated. Should I read in a string and then convert that to double values or is there a simpler way?
Thanks in advance.
Code:
#include <QTGui>
#include <QApplication>
#include <QString>
#include <QTextStream>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextStream cin(stdin, QIODevice::ReadOnly);
QTextStream cout(stdout, QIODevice::WriteOnly);
double mark1, mark2, mark3;
double passMarkNeeded = 0;
QInputDialog::getDouble(0, "Enter marks", "Marks", 1);
cin >> mark1 >> mark2 >> mark3;
cout << "User entered " << mark1 << mark2 << mark3;
return EXIT_SUCCESS;
}
Obviously you cannot use QInputDialog::getDouble because it won't allow you to input 3 values separated by commas. You should use QInputDialog::getText, QString::split and QString::toDouble:
QStringList list = QInputDialog::getText(0, "Input values", "Input values:").split(",");
if (list.count() == 3) {
double a = list[0].toDouble(),
b = list[1].toDouble(),
c = list[2].toDouble();
qDebug() << "Values:" << a << b << c;
}
I'm not sure why you use QInputDialog and the standard input (cin). QInputDialog is for GUI apps, and cin is console apps. It's strange and pointless to use them together in such a way.

How to parse dynamic response using QtSoap?

I have currently the response of type:
<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><StartBuisnessResponse xmlns=\"http://test.com/kerosene/mytest/\"><StartBuisnessResult><Commodity><_price>45</_price></Commodity><Commodity><_price>36</_price></Commodity></StartBuisnessResult></StartBuisnessResponse></soap:Body></soap:Envelope>
Here, the node is dynamic. In such a case, I am not able to find a way to parse the response SOAP XML using QtSoap.
This is the Code which works for fetching the first commodity:
QString str("<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><StartBuisnessResponse xmlns=\"http://cg.nic.in/kerosene/finotest/\"><StartBuisnessResult><Commodity><_price>45</_price></Commodity><Commodity><_price>36</_price></Commodity></StartBuisnessResult></StartBuisnessResponse></soap:Body></soap:Envelope>");
QByteArray *arr = new QByteArray();
arr->append(str);
QtSoapMessage *testMsg = new QtSoapMessage();
testMsg->setContent(*arr);
const QtSoapType &testCont = testMsg->returnValue();
const QtSoapType &price = testCont["Commodity"];
qDebug() << "The value of the _price here is " << price["_price"].value().toString();
But how do I traverse through the subsequent nodes in this case? Any idea?
If you follow the example shown on Qt Solutions QtSoap that they have for Google, you should be on your way with it.
http://doc.qt.digia.com/solutions/4/qtsoap/index.html
http://doc.qt.digia.com/solutions/4/qtsoap/google-example.html
An alternative if you don't want to try that is to use the QXmlStreamReader:
http://qt-project.org/doc/qt-4.8/qxmlstreamreader.html#details
Here is some quick code to get out the _price information from this:
// add "QT += xml" to your .pro
#include <QXmlStreamReader>
#include <QDebug>
QXmlStreamReader xml(str);
while (!xml.atEnd())
{
if (xml.readNextStartElement())
qDebug() << qPrintable(xml.name().toString());
if(xml.name().toString() == "_price")
{
qDebug() << "\t" << xml.readElementText().toInt();
}
}
You also have a number of other alternatives available, too. See Qt XML Processing.
Hope that helps.

Read exif metadata of images in Qt

In my Qt app I want to read exif data of images. QImage or QPixmap don't seem to provide such hooks.
Is there any API in Qt that allows reading exif without using external libraries like libexif?
EDIT: This is a duplicate of this
For me, the best choice was easyexif by Mayank Lahiri. You only need to add two files exif.cpp and exif.h to your project.
int main(int argc, char *argv[])
{
for (int i=1; i<argc; ++i){
QFile file(argv[i]);
if (file.open(QIODevice::ReadOnly)){
QByteArray data = file.readAll();
easyexif::EXIFInfo info;
if (int code = info.parseFrom((unsigned char *)data.data(), data.size())){
qDebug() << "Error parsing EXIF: code " << code;
continue;
}
qDebug() << "Camera model : " << info.Model.c_str();
qDebug() << "Original date/time : " << info.DateTimeOriginal.c_str();
} else
qDebug() << "Can't open file:" << argv[i];
}
return 0;
}
Try QExifImageHeader from qt extended framework. qtextended.org is not available for me? but you may search for other download mirrows.
QImageReader has a method named transformation() which is introduced in version 5.5, first you should try that.
You can also check the following link to see how it's done using Windows GDI in Qt, http://amin-ahmadi.com/2015/12/17/how-to-read-image-orientation-in-qt-using-stored-exif/

Newline character into textfile using QFile

i want to put a newline into a txt file, i tried with many alternative with so many help from this forum but i am getting always unknown character always. Please help
for (int i = 0; i < fileDet.size(); i++) {
qDebug() << "Name directory" << fileDet.at(i);
QFile data("output.txt");
if (data.open(QFile::Append)) {
QTextStream out(&data);
out << fileDet.at(i); //<<'\n';
out << QChar((int)'\n');
}
data.close();
}
Try out << endl;
When you open the file:
data.open(QFile::Append | QFile::Text)

Resources