When wrapping a Qt UI around back-end code using boost::filesystem one frequently needs to convert boost::filesystem::path to QString and vice versa.
What is the best way way to do these conversions that:
Is cross-platform
Losslessly preserves encoding
Produces QStrings containing regular slashes on all platforms, as is Qt's policy.
Is efficient and avoids unnecessary copies
This is what I'm currently using, but suggestions for improvements are very much welcome.
boost::filesystem::path PathFromQString(const QString & filePath)
{
#ifdef _WIN32
auto * wptr = reinterpret_cast<const wchar_t*>(filePath.utf16());
return boost::filesystem::path(wptr, wptr + filePath.size());
#else
return boost::filesystem::path(filePath.toStdString());
#endif
}
QString QStringFromPath(const boost::filesystem::path & filePath)
{
#ifdef _WIN32
return QString::fromStdWString(filePath.generic_wstring());
#else
return QString::fromStdString(filePath.native());
#endif
}
Related
In my Qt GUI app I use libwebrtc. From one on callbacks I want to emit signal with data, which is std::string. As core app logic use QString, I want convert std::string to Qstring.
I try following:
QString::fromStdString(stdstr)
QString::fromLatin1(stdstr.data())
Both of this return broken text, something like this
Only working way for me was
QString qstr;
for(uint i =0; i< stdstr.length(); i++)
qstr.append(stdstr.at(i));
Here my thoughts about reason of problem:
Encoding problems.
Binary problems
About encoding, libwebrtc should return std::string in UTF-8 by default, same as QString.
About binary. As I understand Qt built with GCC and corresponding stdlib, but libwebrtc build with CLang and libc++. For building I also specify usinng QMAKE_CXXFLAGS += -stdlib=libc++
What is correct way to convert types here?
UPD
I compare length of converted string and source string, they are very different.
For std::string I get 64, and for converted QString I get 5.
UPD2
Here is full function and corresponding slot for SPDGen signal
void foo(const webrtc::IceCandidateInterface *candidate) override {
std::string str;
candidate->ToString(&str);
QString qstr = QString::fromStdString(str);
qDebug() << qstr;
Q_EMIT SPDGen(qstr);
}
connect(conductor, &Conductor::SPDGen, this, [=](QString value){
ui->textEdit->setText(value);
});
Using console, I want to write the desired user's input into a file via getline function inside the wFile function and then read it. I face with logical error during Runtime; whatever I as user write doesn't type into the output terminal and it doesn't succeed more steps. Apparently fwrite function with this feature in the libraries exists, but I want to write my own code differently this way. I think I must have neglected a point. Here's the code:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <String>
#include <cstdlib>
using namespace std;
void wFile(QString Filename)
{
QFile mFile(Filename);
QTextStream str(&mFile);
qDebug() << "what do you want to write in the desired file: ";
istream& getline (istream& is, string& str);
if (!mFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
mFile.flush();
mFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename ="P:/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
Spoiler alarm: At the very end of this answer, there is a very simple recommendation for a fix.
What OP did
Concerning istream& getline (istream& is, string& str); in wFile(QString Filename):
This declares function getline() in function wFile().
This is a valid declaration concerning C++.
Concerning the sample code, I missed the respective headers. IMHO,
#include <istream> and
#include <string>
are required to make this compiling.
However, it is possible that the existing #includes include them indirectly. So, OP's code may even compile without them.
Declaring functions, which are not used as well as re-declaring functions which are already declared is somehow useless but not wrong.
To demonstrate this, I made a small sample:
#include <cstdio>
#include <istream>
#include <string>
void func()
{
puts("in func()\n");
std::istream& getline(std::istream&, std::string&);
// Even duplicated prototyping is accepted without complaints:
std::istream& getline(std::istream&, std::string&);
}
int main ()
{
func();
return 0;
}
compiles and runs perfectly.
Output:
in func()
Live Demo on coliru
What OP (probably) wanted
Using console, I want to write the desired user's input into a file via getline function inside the wFile function and then read it.
This sounds a bit confusing to me. std::getline(std::cin, ) can be used to read user input from console. May be, it's a bit bad wording only.
Assuming, the OP wanted to read input from console, obviously, declaring a function is not sufficient – it must be called to become effective:
#include <iostream>
void func()
{
std::cout << "Enter file name: ";
std::string fileName; std::getline(std::cin, fileName);
std::cout << "Got file name '" << fileName << "'\n");
}
int main ()
{
func();
return 0;
}
Output:
Enter file name: test.txt↵
Got file name 'test.txt'
Live Demo on coliru
C++ std vs. Qt
Qt is undoubtly built on top of the C++ std library. However, though it's possible it is not recommended to mix both APIs when it can be prevented (or there aren't specific reasons to do so).
Both, Qt and C++ std, are a possibility to write portable software.
Qt covers a lot of things which are provided in the std library as well but a lot of other things additionally which are not or not yet part of std. In some cases, the Qt is a bit less generic but more convenient though this is my personal opinion. IMHO, the following explains how I came to this:
std::string vs. QString
std::string stores a sequence of chars. The meaning of chars when exposed as glyph (e.g. printing on console or displaying in a window) depends on the encoding which is used in this exposing. There are lot of encodings which interprete the numbers in the chars in distinct ways.
Example:
std::string text = "\xc3\xbc";
Decoded/displayed with
Windows-1252: ü
UTF-8: ü
Based on character type of std::string, it is not possible to determine the encoding. Hence, an additional hint must be provided to decode this properly.
(AFAIK, it is similar for std::wstring and wchar_t.)
QString stores a sequence of Unicode characters. So, one universal encoding was chosen by design to mitigate the "encoding hell".
As long as the program operates on QString, no encoding issues should be expected. The same is true when combining QString with other functions of Qt. However, it becomes a bit more complicated when "leaving the Qt universe" – e.g. storing contents of a std::string to QString.
This is the point where the programmer has to provide the additional hint for the encoding of the contents in std::string. QString provides a lot of from...() and to...() methods which can be used to re-encode contents but the application programmer is still responsible to chose the right one.
Assuming that the intended contents of text should have been the ü (i.e. UTF-8 encoding), this can be converted to QString (and back) by:
// std::string (UTF-8) -> QString
std::string text = "\xc3\xbc";
QString qText = QString::fromUtf8(text.c_str());
// QString -> std::string (UTF-8)
std::string text2 = qText.toUtf8();
This has to be considered when input from std::cin shall be passed to QString:
std::cout << "Enter file name: ";
std::string input; std::getline(std::cin, input);
QString qFileName = QString::fromLocal8Bit(input);
And even now, the code contains a little flaw – the locale of std::cin might have changed with std::ios::imbue(). I must admit that I cannot say much more about this. (In daily work, I try to prevent this topic at all e.g. by not relying on Console input which I consider especially critical on Windows – the OS on which we usually deploy to customers.)
Instead, a last note about OP's code:
How to fix it
Remembering my above recommendation (not to mix std and Qt if not necessary), this can be done in Qt exclusively:
QTextStream qtin(stdin);
qtin.readline();
I must admit that I never did it by myself but found this in the Qt forum: Re: stdin reading.
I have a Qt project, there I have an Object, which is going to be copied a lot of time. Therefor I would like to add move semantics.
#ifndef OBJECTTOCOPY_H
#define OBJECTTOCOPY_H
#include <QColor>
#include <QString>
#include <QDataStream>
namespace level_1 {
namespace level_2 {
class ObjectToCopy {
public:
explicit ObjectToCopy(const QString& _name = "", const QColor& colorBody = QColor() );
// MOVE
ObjectToCopy(ObjectToCopy && other);
static quint32 _valueInt32;
static quint16 _valueInt16;
QString _name;
QColor _colorBody;
private:
};
}
}
#endif // OBJECTTOCOPY_H
How do I steal the pointers of the member variables, since they are no pointers?
ObjectToCopy::ObjectToCopy (ObjectToCopy&& other)
: _valueInt32( other._valueInt32 )
, _valueInt16( other._valueInt16 )
, _name( other._name )
, _colorBody( other._colorBody )
{
other._valueInt32 = 0;
other._valueInt16 = 0;
other.name.clear();
other._colorBody = QColor();
}
Does that make sense for non-pointers?
Is it ok to reset QString 's like string.clear(); to mark that for the garbage collector?
How could I reset a QColor object?
You can add move semantics of course, but in your case there is no need in this at all. quint32, quint16 are moved by copying. QColor is wrapper around union and has no move constructor (and doesn't need one) and will also be moved by copying. QString is reference counted type in QT. It has move constructor in recent versions of library, but the difference in speed will be minimal (difference between swapping pointer and incrementing reference counter).
You are looking for std::move:
ObjectToCopy::ObjectToCopy (ObjectToCopy&& other)
: _valueInt32( other._valueInt32 )
, _valueInt16( other._valueInt16 )
, _name( std::move(other._name) )
, _colorBody( std::move(other._colorBody) )
{
other._valueInt32 = 0; //probably not necessary
other._valueInt16 = 0; //probably not necessary
//other.name.clear(); //not necessary
//other._colorBody = nullptr; //not necessary
}
It makes sense to move non-pointers. You are in the process of making such an object. Moving integers doesn't help, but doesn't hurt either, so you may as well do it for consistancy. Moving things that don't have a move constructor also works: If no move constructor is available the copy constructor is used (moving is not always better, but not worse either).
The implementation above says "move by copying the ints and moving the name and the _colorBody".
Make sure you do not read from variables you moved from.
It is ok, but not necessary. other is supposed to be a temporary that will get destroyed anyways. (C++ does not have a garbage collector in your sense)
Also once an object is moved from it tends to be in the cleared state like for QString, but that is not always the case.
You cannot really. You can assign a default constructed one like other._colorBody = QColor(); but that just means it sets the color to black. A QColor cannot be empty, it always has some color.
Also read What are move semantics?
Is it possible to take pointer to QByteArray's internal T* data and destroy QByteArray itself so that the pointer remains unreleased? I would like to use it in the something similar to the following scenario:
const char* File::readAllBytes(const String& path, u64& outCount) {
QFile file(*static_cast<QString*>(path.internal()));
outCount = static_cast<u64>(file.size());
if (!file.open(QIODevice::ReadOnly)) gException("Failed to open file");
const QByteArray array = file.readAll();
return array.steal();
}
No, you can't steal QByteArray's pointer unless it has been constructed with QByteArray::fromRawData, which is not the case. However you can create char array manually and read data from file to it using QFile::read(char * data, qint64 maxSize). You will then decide where to pass the pointer and when to delete[] it.
Note that this is not considered good practice. You should use managed allocations whenever you can, and Qt provides enough to cover most of possible use cases. You should not do this unless you're trying to do something really low-level.
Note that many of Qt classes, including QString and QByteArray, use copy-on-write strategy, so you generally should not be afraid of copying them and passing them to another context.
No, but you can easily sidestep the problem by not using QByteArray:
const char* File::readAllBytes(const String& path, u64& outCount) {
QFile file(*static_cast<QString*>(path.internal()));
if (!file.open(QIODevice::ReadOnly)) return nullptr;
auto N = file.bytesAvailable();
char *data = malloc(N);
outCount = file.read(data, N);
return data;
}
The solution above also assumes that the consumer of your data is aware of the need to free the data.
Alas, the manual memory management called for with such an API is a bad idea. If you wish not to use Qt classes in your API, you should be using std::vector<char> instead:
std::vector<char> File::readAllBytes(const String& path) {
std::vector<char> result;
QFile file(*static_cast<QString*>(path.internal()));
if (!file.open(QIODevice::ReadOnly)) return result;
result.resize(file.bytesAvailable());
auto count = file.read(result.data(), result.size());
result.resize(count);
return result;
}
I smell that String is some sort of a framework-independent string wrapper. Perhaps you could settle on std::u16string to carry the same UTF16 data as QString would.
Is there an easy way to use QMatrix4x4 with OpenGL functions, specifically glMultMatrixf?
If I understand this right, I'd have to transpose the matrix, and be sure to convert qreal (which can be either float or double depending on the underlying system) to GLfloat.
Isn't there a function which does this for me?
I also have the same problem with QVector3D, which again I need as GLfloat array in the function glVertex3fv.
First I want to mention that QMatrix4x4 has built-in operators for matrix multiplication (with a second matrix, a vector or a scalar). However, your question still needs an answer, as you want to pass a matrix to OpenGL sooner or later.
QMatrix4x4 uses qreals for internal representation. While the class is intended to be used with OpenGL directly (using constData() as suggested by Bart in his answer), you can make sure you pass it to the corresponding OpenGL function depending on the type, if you want to keep platform compatibility (on embedded devices, qreal is float!):
// these are defined in the OpenGL headers:
void glMultMatrixf(const GLfloat *m);
void glMultMatrixd(const GLdouble *m);
// add overloaded functions which call the underlying OpenGL function
inline void glMultMatrix(const GLfloat *m) { glMultMatrixf(m); }
inline void glMultMatrix(const GLdouble *m) { glMultMatrixd(m); }
// add an overload for QMatrix4x4 for convenience
inline void glMultMatrix(const QMatrix4x4 &m) { glMultMatrix(m.constData()); }
You can also use this mechanism for vectors, here the glVertex* family, where it makes even more sense because of the number of components the "raw pointer" overloads need to consider, but the object oriented overloads can do automatically for you:
inline void glVertex2v(const GLfloat *v) { glVertex2fv(v); }
inline void glVertex2v(const GLdouble *v) { glVertex2dv(v); }
inline void glVertex3v(const GLfloat *v) { glVertex3fv(v); }
inline void glVertex3v(const GLdouble *v) { glVertex3dv(v); }
inline void glVertex4v(const GLfloat *v) { glVertex4fv(v); }
inline void glVertex4v(const GLdouble *v) { glVertex4dv(v); }
// Note that QVectorND use floats, but we check this during compile time...
Q_STATIC_ASSERT(sizeof(QVector2D) == 2*sizeof(float));
Q_STATIC_ASSERT(sizeof(QVector3D) == 3*sizeof(float));
Q_STATIC_ASSERT(sizeof(QVector4D) == 4*sizeof(float));
inline void glVertex(const QVector2D &v) { glVertex2v(reinterpret_cast<const float*>(&v)); }
inline void glVertex(const QVector3D &v) { glVertex3v(reinterpret_cast<const float*>(&v)); }
inline void glVertex(const QVector4D &v) { glVertex4v(reinterpret_cast<const float*>(&v)); }
// Even for QPointF we can do it!
Q_STATIC_ASSERT(sizeof(QPointF) == 2*sizeof(qreal));
inline void glVertex(const QPointF &v) { glVertex4v(reinterpret_cast<const qreal*>(&v)); }
So your code keeps valid if the following changes are made:
Qt changes the representation of QVector* / QMatrix to use floats / doubles respectively,
Your code changes the number of components of vectors
... while especially the second isn't the case when using raw OpenGL commands like glVertex3f.
The Q_STATIC_ASSERTions in the code above are only defined since Qt 5.0. If you are using Qt4 (or code with Qt4 compatibility), add this in some global header file / before your definitions: http://ideone.com/VDPUSg [source: Qt5 / qglobal.h]
qreal is defined to be a double on all platforms, except for ARM architectures. So most likely for you they are doubles.
That said, yes, you can use your QMatrix4x4 perfectly fine with OpenGL, using the constData() method. Of course with a double type you would either have to use glMultMatrixd, or create a float matrix out of it. Which might not be what you want to do. There are various examples by Qt which use the matrix type in their OpenGL demos.
I personally never use Qt's matrix and vector types for my OpenGL code though (even though I extensively use Qt), but rather go for a library like Eigen, GLM, or something else suitable.