Is there a QString
function which takes an int and outputs it as a QString
?
Use QString::number()
:
And if you want to put it into string within some text context, forget about +
operator. Simply do:
// Qt 5 + C++11
auto i = 13;
auto printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 5
int i = 13;
QString printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 4
int i = 13;
QString printable = QString::fromLatin1("My magic number is %1. That's all!").arg(i);
Moreover to convert whatever you want, you can use QVariant
. For an int
to a QString
you get:
A float
to a string
or a string
to a float
:
How do I set color of text and background of a QLabel
?
The best and recommended way is to use Qt Style Sheet.
To change the text color and background color of a QLabel
, here is what I would do :
QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");
You could also avoid using Qt Style Sheets and change the QPalette
colors of your QLabel
, but you might get different results on different platforms and/or styles.
As Qt documentation states :
Using a QPalette isn’t guaranteed to work for all styles, because style authors are restricted by the different platforms’ guidelines and by the native theme engine.
But you could do something like this :
QPalette palette = ui->pLabel->palette();
palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
ui->pLabel->setPalette(palette);
But as I said, I strongly suggest not to use the palette and go for Qt Style Sheet.
You can use QPalette, however you must set setAutoFillBackground(true);
to enable background color
QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);
sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");
It works fine on Windows and Ubuntu, I haven’t played with any other OS.
Note: Please see QPalette, color role section for more details
I add this answer because I think it could be useful to anybody.
I step into the problem of setting RGBA colors (that is, RGB color with an Alpha value for transparency) for color display labels in my painting application.
As I came across the first answer, I was unable to set an RGBA color. I have also tried things like:
myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())
where color
is an RGBA color.
So, my dirty solution was to extend QLabel
and override paintEvent()
method filling its bounding rect.
Today, I’ve open up the qt-assistant
and read the style reference properties list. Affortunately, it has an example that states the following:
QLineEdit { background-color: rgb(255, 0, 0) }
Thats open up my mind in doing something like the code below, as an example:
myLabel= QLabel()
myLabel.setAutoFillBackground(True) # This is important!!
color = QtGui.QColor(233, 10, 150)
alpha = 140
values = "{r}, {g}, {b}, {a}".format(r = color.red(),
g = color.green(),
b = color.blue(),
a = alpha
)
myLabel.setStyleSheet("QLabel { background-color: rgba("+values+"); }")
Note that setAutoFillBackground()
set in False
will not make it work.
Regards,
I am trying to do something like this:
but the code doesn’t compile. How to output the content of qstring into the console (e.g. for debugging purposes or other reasons)? How to convert QString
to std::string
?
One of the things you should remember when converting QString
to std::string
is the fact that QString
is UTF-16 encoded while std::string
… May have any encodings.
So the best would be either:
QString qs;
// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();
// or this if you're on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();
The suggested (accepted) method may work if you specify codec.
You can use:
Here’s reference documentation for QString
.
If your ultimate aim is to get debugging messages to the console, you can use qDebug().
You can use like,
qDebug()<<string;
which will print the contents to the console.
This way is better than converting it into std::string
just for the sake of debugging messages.
I’m using Qt4 and C++ for making some programs in computer graphics. I need to be able to print some variables in my console at run-time, not debugging, but cout
doesn’t seem to work even if I add the libraries. Is there a way to do this?
If it is good enough to print to stderr
, you can use the following streams originally intended for debugging:
#include<QDebug>
//qInfo is qt5.5+ only.
qInfo() << "C++ Style Info Message";
qInfo( "C Style Info Message" );
qDebug() << "C++ Style Debug Message";
qDebug( "C Style Debug Message" );
qWarning() << "C++ Style Warning Message";
qWarning( "C Style Warning Message" );
qCritical() << "C++ Style Critical Error Message";
qCritical( "C Style Critical Error Message" );
// qFatal does not have a C++ style method.
qFatal( "C Style Fatal Error Message" );
Though as pointed out in the comments, bear in mind qDebug messages are removed if QT_NO_DEBUG_OUTPUT
is defined
If you need stdout you could try something like this (as Kyle Strand has pointed out):
You could then call as follows:
I found this most useful:
stdout
If you want something that, like std::cout
, writes to your application’s standard output, you can simply do the following (credit to CapelliC):
If you want to avoid creating a temporary QTextStream
object, follow Yakk’s suggestion in the comments below of creating a function to return a static
handle for stdout
:
inline QTextStream& qStdout()
{
static QTextStream r{stdout};
return r;
}
...
foreach(QString x, strings)
qStdout() << x << endl;
Remember to flush
the stream periodically to ensure the output is actually printed.
stderr
Note that the above technique can also be used for other outputs. However, there are more readable ways to write to stderr
(credit to Goz and the comments below his answer):
qDebug() << "Debug Message"; // CAN BE REMOVED AT COMPILE TIME!
qWarning() << "Warning Message";
qCritical() << "Critical Error Message";
qFatal("Fatal Error Message"); // WILL KILL THE PROGRAM!
qDebug()
is closed if QT_NO_DEBUG_OUTPUT
is turned on at compile-time.
(Goz notes in a comment that for non-console apps, these can print to a different stream than stderr
.)
NOTE: All of the Qt print methods assume that const char*
arguments are ISO-8859-1 encoded strings with terminating \0
characters.
Edit: Some people started to mark my question as a duplicate. Do not forget that many similar questions existed when I asked this one (see e.g. the list below). However, none of these answers solved my problem. After a long search I found a comment which had been ignored by all users pointing to the missing lib. Now, many months later, the comment has been changed to an answer. However, when I answered this question by msyself I intended to help other people by directly providing the solution. This should not be forgotten and so far my answer helped a lot of people. Therefore my question is definitely not a duplicate. By the way: The accepted answer within the provided link on top does not solve the problem!
Yes, i used the search:
Failed to load platform plugin “windows”. Available platforms are : Error
Deploying Qt C++ Application from Visual Studio qwindows.dll error
failed to load platform plugin “windows” Available platforms are: windows, minimal
However, in my case the problem still persists. I am using Qt 5.1.1 with Visual Studio 2012 and developed my Application on Windows 7 with Qt Creator 2.8.1. Application is compiled in “Release”-mode and can be executed if directly started with Qt Creator.
However, when starting from the “release”-Folder, i get the following message:
This application failed to start because it could not find or load the Qt platform plugin “windows”. Available platform plugins are: minimal, offscreen, windows.
Folder structure looks like this:
release
+ gui.exe
+ icudt51.dll
+ icuin51.dll
+ icuuc51.dll
+ libGLESv2.dll
+ Qt5Core.dll
+ Qt5Gui.dll
+ Qt5Widgets.dll
+ platforms
Platforms is the folder directly copied from Qt.1\5.1.1 including e.g. qwindows.dll. Does not matter if I rename it to “platform” as some other users did. Qt is still not finding the “platform plugin windows”, where is my mistake?
Okay, as posted here https://stackoverflow.com/a/17271172/1458552 without much attention by other users:
The libEGL.dll was missing! Even though this has not been reported when trying to start the application (all other *.dlls such as Qt5Gui.dll had been reported).
I created a platforms directory next to my exe location and put qwindows.dll inside, but I still received the “Failed to load platform plugin”windows“. Available platforms are: windows” error.
I had copied qwindows.dll from C:.1, which is not the right location. I looked at the debug log from running in Qt Creator and found that my app was looking in C:.1\5.1.1_32when it ran in the debugger.
When I copied from C:.1\5.1.1_32, everything worked fine.
The release is likely missing a library/plugin or the library is in the wrong directory and or from the wrong directory.
Create a folder named “platforms” in the same directory as your application.exe file. Copy and paste the qwindows.dll, found in the /bin of whichever compiler you used to release your application, into the “platforms” folder. Like magic it works. If the .dll is not there check plugins/platforms/ ( with plugins/ being in the same directory as bin/ ) : PfunnyGuy’s comment.
It seems like a common issue is that the .dll was taken from the wrong compiler bin. Be sure to copy your the qwindows.dll from the same compiler as the one used to release your app.
Also another helpful tip, Qt comes with platform console applications that will add all dependencies (including ones like qwindows.dll and libEGL.dll) into the folder of your deployed executable. The application for windows is called windeployqt and the documentation can be found here http://doc.qt.io/qt-5/windows-deployment.html.
How can I add external library into a project built by Qt Creator RC1 (version 0.9.2)? For example, the win32 function EnumProcesses()
requires Psapi.lib
to be added in the project to build.
The proper way to do this is like this:
This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any ‘lib’ prefix). Of course, if you are including a Windows specific lib, this really doesn’t matter.
In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_
variable, e.g.:
Are you using qmake
projects? If so, you can add an external library using the LIBS
variable. E.g:
LIBS += C:Files
won’t work because you’re using white-spaces in Program Files. In this case you have to add quotes, so the result will look like this: LIBS += “C:Files”. I recommend placing libraries in non white-space locations ;-)
What is the most basic way to do it?
If by string you mean std::string
you can do it with this method:
QString QString::fromStdString(const std::string & str)
If by string you mean Ascii encoded const char *
then you can use this method:
QString QString::fromAscii(const char * str, int size = -1)
If you have const char *
encoded with system encoding that can be read with QTextCodec::codecForLocale() then you should use this method:
QString QString::fromLocal8Bit(const char * str, int size = -1)
const char* str = "zażółć gęślą jaźń"; // latin2 source file and system encoding
QString qstr = QString::fromLocal8Bit(str);
If you have const char *
that’s UTF8 encoded then you’ll need to use this method:
QString QString::fromUtf8(const char * str, int size = -1)
const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char*
QString qstr = QString::fromUtf8(str);
There’s also method for const ushort *
containing UTF16 encoded string:
QString QString::fromUtf16(const ushort * unicode, int size = -1)
If compiled with STL compatibility, QString
has a static method to convert a std::string
to a QString
:
Alternative way:
This has the advantage of not using .c_str()
which might cause the std::string
to copy itself in case there is no place to add the '\0'
at the end.
I wrote application for linux which uses Qt5.
But when I am trying to launch it on the linux without Qt SDK installed, the output in console is:
Failed to load platform plugin “xcb”. Available platforms are:
How can I fix this? May be I need to copy some plugin file? When I use ubuntu with Qt5 installed, but I rename Qt directory, the same problem occurs. So, it uses some file from Qt directory…
UPDATE: when I create in the app dir “platforms” folder with the file libqxcb.so, the app still doesnot start, but the error message changes:
Failed to load platform plugin “xcb”. Available platforms are:
xcb
How can this happen? How can platform plugin be available but can’t be loaded?
Use ldd (man ldd) to show shared library dependencies. Running this on libqxcb.so
shows that xcb depends on libQt5DBus.so.5 in addition to libQt5Core.so.5 and libQt5Gui.so.5 (and many other system libs). Add libQt5DBus.so.5 to your collection of shared libs and you should be ready to move on.
As was posted earlier, you need to make sure you install the platform plugins when you deploy your application. Depending on how you want to deploy things, there are two methods to tell your application where the platform plugins (e.g. platforms/plugins/libqxcb.so) are at runtime which may work for you.
The first is to export the path to the directory through the QT_QPA_PLATFORM_PLUGIN_PATH variable.
or
The other option, which I prefer is to create a qt.conf file in the same directory as your executable. The contents of which would be:
More information regarding this can be found here and at using qt.conf
I tried to start my binary, compiled with Qt 5.7, on Ubuntu 16.04 LTS where Qt 5.5 is preinstalled. Expectedly, it didn’t work as is.
At first, I inspected the binary itself with ldd
as was suggested here, and satisfied all “not found” dependencies. Then this notorious This application failed to start because it could not find or load the Qt platform plugin "xcb"
error was thrown in.
What should be done on Linux to resolve this
At first, you should create platforms
directory where your binary is, because it is the place where Qt looks for XCB library. Copy libqxcb.so
there. I wonder why authors of other answers didn’t mention this.
Then you may want to run your binary with QT_DEBUG_PLUGINS=1
environment variable set to check what dependencies of libqxcb.so
unsatisfied. (You may also use ldd
for this as suggested in the accepted answer).
The command output may look like this:
me@xerus:/media/sf_Qt/Package$ LD_LIBRARY_PATH=. QT_DEBUG_PLUGINS=1 ./Binary
QFactoryLoader::QFactoryLoader() checking directory path "/media/sf_Qt/Package/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "/media/sf_Qt/Package/platforms/libqxcb.so"
Found metadata in lib /media/sf_Qt/Package/platforms/libqxcb.so, metadata=
{
"IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
"MetaData": {
"Keys": [
"xcb"
]
},
"className": "QXcbIntegrationPlugin",
"debug": false,
"version": 329472
}
Got keys from plugin meta data ("xcb")
loaded library "/media/sf_Qt/Package/platforms/libqxcb.so"
QLibraryPrivate::loadPlugin failed on "/media/sf_Qt/Package/platforms/libqxcb.so" : "Cannot load library /media/sf_Qt/Package/platforms/libqxcb.so: (/usr/lib/x86_64-linux-gnu/libQt5DBus.so.5: version `Qt_5' not found (required by ./libQt5XcbQpa.so.5))"
This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".
Available platform plugins are: xcb.
Reinstalling the application may fix this problem.
Aborted (core dumped)
Note the failing libQt5DBus.so.5
library. Copy it to your libraries path, in my case it was the same directory where my binary is (hence LD_LIBRARY_PATH=.
). Repeat this process until all dependencies are satisfied.
P.S. thanks to the author of this answer for QT_DEBUG_PLUGINS=1
.
I’m playing around with Qt, and I want to create a simple pause between two commands. However it won’t seem to let me use Sleep(int mili);
, and I can’t find any obvious wait functions.
I am basically just making a console application to test some class code which will later be included in a proper Qt GUI, so for now I’m not bothered about breaking the whole event-driven model.
This previous question mentions using qSleep()
which is in the QtTest
module. To avoid the overhead linking in the QtTest
module, looking at the source for that function you could just make your own copy and call it. It uses defines to call either Windows Sleep()
or Linux nanosleep()
.
I wrote a super simple delay function for an application I developed in Qt.
I would advise you to use this code rather than the sleep function as it won’t let your GUI freeze.
Here is the code:
void delay()
{
QTime dieTime= QTime::currentTime().addSecs(1);
while (QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
To delay an event by n seconds - use addSecs(n)
.
From Qt5 onwards we can also use
Static Public Members of QThread
I have a software in ubuntu that requires me to run qmake to generate the Makefile.
However, running qmake gives back this error,
I have installed what I thought to be the required packages using,
But the error didn’t go away.
Any help on this would be gladly appreciated!
sudo apt-get install qt5-default
works for me.
$ aptitude show qt5-default</pre></code>
tells that</p>
<blockquote>
<p>This package sets Qt 5 to be the default Qt version to be used when using
development binaries like qmake. It provides a default configuration for
qtchooser, but does not prevent alternative Qt installations from being used.</p>
</blockquote>
#### Answer 2 (score 28)
You could check path to qmake using `which qmake`.
Consider install `qt4-default` or `qt5-default` depends what version of qt you want use.
You could also use <a href="http://manpages.ubuntu.com/manpages/utopic/man1/qtchooser.1.html">qtchooser</a> - a wrapper used to select between Qt development binary versions.
#### Answer 3 (score 12)
For others in my situation, the solution was:
```c
qmake -qt=qt5
This was on Ubuntu 14.04 after install qt5-qmake. qmake was a symlink to qtchooser which takes the -qt argument.
I’m using the Qt Designer.
I want to create a QVBoxLayout
which will automatically expand to fill the whole window.
The layout of the QVBoxLayout
remains fixed.
How can I cause the QVBoxLayout
to expand and fill the entire window through the designer?
After creating your QVBoxLayout
in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout
, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout
should now stretch to fit the window and will resize automatically when the entire window is resized.
According to the documentation, there needs to be a top level layout set.
A top level layout is necessary to ensure that your widgets will resize correctly when its window is resized. To check if you have set a top level layout, preview your widget and attempt to resize the window by dragging the size grip.
You can set one by clearing the selection and right clicking on the form itself and choosing one of the layouts available in the context menu.
I’ve tried to find a “fit to screen” property but there is no such.
But setting widget’s “maximumSize” to a “some big number” ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.
I have a QString
in my sources. So I need to convert it to integer without “Kb”.
I tried Abcd.toInt()
but it does not work.
You don’t have all digit characters in your string. So you have to split by space
QString Abcd = "123.5 Kb";
Abcd.split(" ")[0].toInt(); //convert the first part to Int
Abcd.split(" ")[0].toDouble(); //convert the first part to double
Abcd.split(" ")[0].toFloat(); //convert the first part to float
Update: I am updating an old answer. That was a straight forward answer to the specific question, with a strict assumption. However as noted by @DomTomCat in comments and @Mikhail in answer, In general one should always check whether the operation is successful or not. So using a boolean flag is necessary.
Also if you are taking that string as user input, then you should also be doubtful about whether the string is really splitable with space. If there is a possibility that the assumption may break then a regex verifier is more preferable. A regex like the following will extract the floating point value and the prefix character of ‘b’. Then you can safely convert the captured strings to double.
You can have an utility function like the following
QPair<double, QString> split_size_str(const QString& str){
QRegExp regex("([0-9]*\\.?[0-9]+)\\s+(\\w[bB])");
int pos = regex.indexIn(str);
QStringList captures = regex.capturedTexts();
if(captures.count() > 1){
double value = captures[1].toDouble(); // should succeed as regex matched
QString unit = captures[2]; // should succeed as regex matched
return qMakePair(value, unit);
}
return qMakePair(0.0f, QString());
}
Don’t forget to check if the conversion was successful!
bool ok;
auto str= tr("1337");
str.toDouble(&ok); // returns 1337.0, ok set to true
auto strr= tr("LEET");
strr.toDouble(&ok); // returns 0.0, ok set to false
I am trying to write into a file and if the file doesn’t exist create it. I have searched on the internet and nothing worked for me.
My code looks currently like this:
QString filename="Data.txt";
QFile file( filename );
if ( file.open(QIODevice::ReadWrite) )
{
QTextStream stream( &file );
stream << "something" << endl;
}
If I create a text file called Data in the directory, it remains empty. If I don’t create anything it doesn’t create the file either. I don’t know what to do with this, this isn’t the first way in which I tried to create/write into a file and none of the ways worked.
Thanks for your answers.
Are you sure you’re in the right directory?
Opening a file without a full path will open it in the current working directory. In most cases this is not what you want. Try changing the first line to
QString filename="c:\\Data.txt"
or
QString filename="c:/Data.txt"
and see if the file is created in c:\
That is weird, everything looks fine, are you sure it does not work for you? Because this main
surely works for me, so I would look somewhere else for the source of your problem.
#include <QFile>
#include <QTextStream>
int main()
{
QString filename = "Data.txt";
QFile file(filename);
if (file.open(QIODevice::ReadWrite)) {
QTextStream stream(&file);
stream << "something" << endl;
}
}
The code you provided is also almost the same as the one provided in detailed description of QTextStream so I am pretty sure, that the problem is elsewhere :)
Also note, that the file is not called Data
but Data.txt
and should be created/located in the directory from which the program was run (not necessarily the one where the executable is located).
#include <QFile>
#include <QCoreApplication>
#include <QTextStream>
int main(int argc, char *argv[])
{
// Create a new file
QFile file("out.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << "This file is generated by Qt\n";
// optional, as QFile destructor will already do it:
file.close();
//this would normally start the event loop, but is not needed for this
//minimal example:
//return app.exec();
return 0;
}
I was trying to convert a QString to char* type by the following methods, but they don’t seem to work.
//QLineEdit *line=new QLineEdit();{just to describe what is line here}
QString temp=line->text();
char *str=(char *)malloc(10);
QByteArray ba=temp.toLatin1();
strcpy(str,ba.data());
Can you elaborate the possible flaw with this method, or give an alternative method?
Well, the Qt FAQ says:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str1 = "Test";
QByteArray ba = str1.toLocal8Bit();
const char *c_str2 = ba.data();
printf("str2: %s", c_str2);
return app.exec();
}
So perhaps you’re having other problems. How exactly doesn’t this work?
Maybe
my_qstring.toStdString().c_str();
or safer, as Federico points out:
It’s far from optimal, but will do the work.
The easiest way to convert a QString to char* is qPrintable(const QString& str), which is a macro expanding to str.toLocal8Bit().constData()
.
I want to display .jpg image in an Qt UI. I checked it online and found http://qt-project.org/doc/qt-4.8/widgets-imageviewer.html. I thought Graphics View will do the same, and also it has codec to display video. How to display images using Graphics View? I went through the libraries, but because I am a totally newbie in Qt, I can’t find a clue to start with. Can you direct me to some resources/examples on how to load and display images in Qt?
Thanks.
#include ...
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QGraphicsPixmapItem item(QPixmap("c:\\test.png"));
scene.addItem(&item);
view.show();
return a.exec();
}
This should work. :) List of supported formats can be found here
You could attach the image (as a pixmap) to a label then add that to your layout…
...
QPixmap image("blah.jpg");
QLabel imageLabel = new QLabel();
imageLabel.setPixmap(image);
mainLayout.addWidget(imageLabel);
...
Apologies, this is using Jambi (Qt for Java) so the syntax is different, but the theory is the same.
If the only thing you want to do is drop in an image onto a widget withouth the complexity of the graphics API, you can also just create a new QWidget and set the background with StyleSheets. Something like this:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ... QWidget *pic = new QWidget(this); pic->setStyleSheet("background-image: url(test.png)"); pic->setGeometry(QRect(50,50,128,128)); ... }
When I try installing the PyQt5 on Windows using the command
I get this error:
I got the pyQt5 from PyQt5 Download.
How can I install PyQt5?
Update:
I installed Qt 5.0.2 for Windows 64-bit (VS 2012, 500 MB)
from the Qt Download page and now I have this error:
And when I execute the command python configure.py --verbose
:
Querying qmake about your Qt installation... Determining the details of your Qt installation... C:\Qt\Qt5.0.2\5.0.2\msvc2012_64\bin\qmake.exe -spec win32-msvc2008 -o qtdetail.m k qtdetail.pro nmake -f qtdetail.mk release 'nmake' não é reconhecido como um comando interno ou externo, um programa operável ou um arquivo em lotes. Error: Failed to determine the detail of your Qt installation. Try again using the --verbose flag to see more detail about the problem.
I added C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin
(contains nmake.exe
) to PATH and I got this error:
Querying qmake about your Qt installation... Determining the details of your Qt installation... C:\Qt\Qt5.0.2\5.0.2\msvc2012_64\bin\qmake.exe -spec win32-msvc2008 -o qtdetail.mk qtdetail.pro nmake -f qtdetail.mk release Microsoft (R) Program Maintenance Utility Version 11.00.50727.1 Copyright (C) Microsoft Corporation. All rights reserved. "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\nmake.exe" -f qtdetail.mk.Release Microsoft (R) Program Maintenance Utility Version 11.00.50727.1 Copyright (C) Microsoft Corporation. All rights reserved. cl -c -nologo -Zm200 -Zc:wchar_t -O2 -MD -GR -W3 -w34100 -w34189 -EHsc -DUNICODE -DWIN32 -DQT_NO_DEBUG -DQT_CORE_LIB -I"..\..\..\..\..\..\..\Qt\Qt5.0.2\5.0.2\msvc2012_64\include" -I"..\..\..\..\..\..\..\Qt\Qt5.0.2\5.0.2\msvc2012_64\include\QtCore" -I"release" -I"..\..\..\..\..\..\..\Qt\Qt5.0.2\5.0.2\msvc2012_64\mkspecs\win32-msvc2008" -Forelease\ @C:\Users\Victor\AppData\Local\Temp\nm68EA.tmp NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\cl.EXE"' : return code '0xc0000135' Stop. NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\nmake.exe"' : return code '0x2' Stop.
The easiest way to install PyQt is to just use the installer (Link in your answer, step #5). If you install python 3.3, the installer will add all of the PyQt5 extras to that python installation automatically. You won’t need to do any compiling (none of: nmake, nmake install, python configure).
All of the build options are available for if you need a custom install (for instance, using a different version of python, where there isn’t an installer provided by riverbank computing).
If you do need to compile your own version of PyQt5, the steps (as you have found) are here, but assume you have python and a compiler installed and in your path. The installed and in your path have been where you have been running into trouble it seems. I’d recommend using the installer version, but you need to install python 3.3 first.
Mainly I use the following command under the cmd
And it works with no problem!
First try this in your Windows cmd window:
If that is successful, it will look something like this:
C:\Windows\System32>pip3 install pyqt5
Collecting pyqt5
Downloading PyQt5-5.9-5.9.1-cp35.cp36.cp37-none-win_amd64.whl (77.2MB)
100% |################################| 77.2MB 13kB/s
Collecting sip<4.20,>=4.19.3 (from pyqt5)
Downloading sip-4.19.3-cp35-none-win_amd64.whl (49kB)
100% |################################| 51kB 984kB/s
Installing collected packages: sip, pyqt5
Successfully installed pyqt5-5.9 sip-4.19.3
If that did not work, you might try this link from SourceForge.
PyQt5 .exe installers for Windows
How to find the installer that’s right for you?
First, determine what version of Python you have and whether you have 32-bit or 64-bit Python. Next, open one of the directories. I’m on Python 3.5 64-bit so I’m looking for a .exe with those specs. When you open a directory on SourceForge, you will see some directories with ONLY .zip or .tar.gz. That’s not what you’re looking for. A good indication of which directory you should click is given by the “Downloads/Week” column. I’ll open the PyQt-5.6 directory in my case.
Here we notice some .exe files:
PyQt-5.6
|_PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x32-2.exe
|_PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
|_PyQt5_gpl-5.6.zip
|_PyQt5_gpl-5.6.tar.gz
I know these are Python 3.5 by Py3.5
in the file name. I am also looking for the 64-bit version so I’ll download PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
. Final answer!
Note: if you try to install a version that’s not compatible with your system, a dialog box will appear immediately after running the .exe. That’s an indication that you’ve chosen the wrong one. I’m not trying to sound like a dbag… I did that several times!
To test a successful install, in your Python interpreter, try to import:
How do I show a message box with Yes/No buttons in Qt, and how do I check which of them was pressed?
I.e. a message box that looks like this:
You would use QMessageBox::question
for that.
Example in a hypothetical widget’s slot:
#include <QApplication>
#include <QMessageBox>
#include <QDebug>
// ...
void MyWidget::someSlot() {
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Test", "Quit?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
qDebug() << "Yes was clicked";
QApplication::quit();
} else {
qDebug() << "Yes was *not* clicked";
}
}
Should work on Qt 4 and 5, requires QT += widgets
on Qt 5, and CONFIG += console
on Win32 to see qDebug()
output.
See the StandardButton
enum to get a list of buttons you can use; the function returns the button that was clicked. You can set a default button with an extra argument (Qt “chooses a suitable default automatically” if you don’t or specify QMessageBox::NoButton
).
You can use the QMessage object to create a Message Box then add buttons :
QT can be as simple as that of Windows. The equivalent code is
if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, "title", "Question", QMessageBox::Yes|QMessageBox::No).exec())
{
}
I have a table view with three columns; I have just passed to write into text file using this code
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(0,"error",file.errorString());
}
QString dd;
for(int row=0; row < model->rowCount(); row++) {
dd = model->item(row,0)->text() + ","
+ model->item(row,1)->text() + ","
+ model->item(row,2)->text();
QTextStream out(&file);
out << dd << endl;
}
But I’m not succeed to read the same file again, I tried this code but I don’t know where is the problem in it
QFile file("/home/hamad/lesson11.txt");
QTextStream in(&file);
QString line = in.readLine();
while(!in.atEnd()) {
QStringList fields = line.split(",");
model->appendRow(fields);
}
Any help please ?
You have to replace string line
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
I’m writing a program in C++ using the Qt library. There is a symbolic link in my home bin directory to the executable. I would like the current working directory of my program to be the directory in which I am with my terminal (ie. the result of the pwd
command). I saw the QDir::currentPath()
function, but it gives back the directory where the binary is.
How can I find my current working directory?
Thank you RedX and Kaz for your answers. I don’t get why by me it gives the path of the exe. I found an other way to do it :
QString pwd("");
char * PWD;
PWD = getenv ("PWD");
pwd.append(PWD);
cout << "Working directory : " << pwd << flush;
It is less elegant than a single line… but it works for me.
Just tested and QDir::currentPath()
does return the path from which I called my executable.
And a symlink does not “exist”. If you are executing an exe from that path you are effectively executing it from the path the symlink points to.
Have you tried QCoreApplication::applicationDirPath()
The title is pretty self-descriptive. I’ve downloaded Qt Creator 2.7.0, and I am trying to compile some basic C++11 code:
I’m receiving the following error:
Yet, according to this article this version of Qt Creator supports C++11. So how do I enable it?
According to this site add
CONFIG += c++11
to your .pro file (see at the bottom of that web page). It requires Qt 5.
The other answers, suggesting
QMAKE_CXXFLAGS += -std=c++11
(or QMAKE_CXXFLAGS += -std=c++0x
)
also work with Qt 4.8 and gcc / clang.
Add this to your .pro file
or
As an alternative for handling both cases addressed in Ali’s excellent answer, I usually add
# With C++11 support
greaterThan(QT_MAJOR_VERSION, 4){
CONFIG += c++11
} else {
QMAKE_CXXFLAGS += -std=c++0x
}
to my project files. This can be handy when you don’t really care much about which Qt version is people using in your team, but you want them to have C++11 enabled in any case.
I want to get QString
from another QString
, when I know necessary indexes. For example: Main string: “This is a string”. I want to create new QString
from first 5 symbols and get “This”.
input : first and last char number.
output : new QString
.
How to create it ?
P.S. Not only first several letters, also from the middle of the line, for example from 5 till 8.
If you do not need to modify the substring, then you can use QStringRef
. The QStringRef
class is a read only wrapper around an existing QString
that references a substring within the existing string. This gives much better performance than creating a new QString
object to contain the sub-string. E.g.
QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"
If you do need to modify the substring, then left()
, mid()
and right()
will do what you need…
Use the left
function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid()
if you want more control.
I am trying to compile a hello world program in Qt Using Qt Creator.
I am getting ‘cl’ is not recognized as an internal or external command.
I am using Windows 7 and Both Vs 2008 and 2010 installed in it. When I use Mingw it is compiling fine but if use vs 2008 it is giving this error.
After Setting Env Path =..;..;C:FilesVisual Studio 9.0also it is showing the same error.
I think cl
isn’t in your path. You need to add it there. The recommended way to do this is to launch a developer command prompt.
Quoting the article Setting the Path and Environment Variables for Command-Line Builds:
To open a Developer Command Prompt window
With the Windows 8 Start screen showing, type Visual Studio Tools. Notice that the search results change as you type; when Visual Studio Tools appears, choose it.
On earlier versions of Windows, choose Start, and then in the search box, type Visual Studio Tools. When Visual Studio Tools appears in the search results, choose it.
In the Visual Studio Tools folder, open the Developer Command Prompt for your version of Visual Studio. (To run as administrator, open the shortcut menu for the Developer Command Prompt and choose Run as Administrator.)
As the article notes, there are several different shortcuts for setting up different toolsets - you need to pick the suitable one.
If you already have a plain Command Prompt window open, you can run the batch file vcvarsall.bat
with the appropriate argument to set up the environment variables. Quoting the same article:
To run vcvarsall.bat
At the command prompt, change to the Visual C++ installation directory. (The location depends on the system and the Visual Studio installation, but a typical location is C:Files (x86)Visual Studio version.) For example, enter:
cd "\Program Files (x86)\Microsoft Visual Studio 12.0\VC" ```</li> <li><p>To configure this Command Prompt window for 32-bit x86 command-line builds, at the command prompt, enter:</p> ```c vcvarsall x86 ```</li> </ol> </blockquote> From the article, the possible arguments are the following: <ul> <li>`x86` (x86 32-bit native)</li> <li>`x86_amd64` (x64 on x86 cross)</li> <li>`x86_arm` (ARM on x86 cross)</li> <li>`amd64` (x64 64-bit native)</li> <li>`amd64_x86` (x86 on x64 cross)</li> <li>`amd64_arm` (ARM on x64 cross)</li> </ul> #### Answer 2 (score 6) <p>I had the same problem. Try to make a bat-file to start the Qt Creator. Add something like this to the bat-file:</p> ```c call "C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat" "C:\QTsdk\qtcreator\bin\qtcreator"
Now I can compile and get:
Make sure you restart your computer after you install the Build Tools.
This was what was causing the error for me.
In Qt, I can get the selected text
of a QComboBox
by using the combobox->currentText()
method. How can I get the selected value
?
I searched for help but I couldn’t find a method currentData()
which I expected to find. I could only find combobox->currentIndex()
Is there a smarter way to do it other than combobox->itemData(combobox->currentIndex())
?
Update: This is no longer necessary as of Qt 5. A currentData()
method has been added http://doc.qt.io/qt-5/qcombobox.html#currentData-prop
It seems you need to do combobox->itemData(combobox->currentIndex())
if you want to get the current data of the QComboBox.
If you are using your own class derived from QComboBox, you can add a currentData()
function.
This one can get the text of current index:
you can set QVariant data for all items, then you can get the value when you need it.
there is an example code for this situation:
ui.comboBoxSheetSize->addItem("128 m", QVariant(128));
ui.comboBoxSheetSize->addItem("256 m", QVariant(256));
ui.comboBoxSheetSize->addItem("512 m", QVariant(512));
ui.comboBoxSheetSize->addItem("1024 m", QVariant(1024));
...
void Page::onComboSheetSizeChanged( int index )
{
int value = ui.comboBoxSheetSize->itemData(index).toInt();
}
by the way, i think i misunderstood your question. i think the way you get data is smart enough?
Installed just the IDE on Windows 7. I want to create a Plain C++ Project (Non-QT Project); however I get an error: No valid kits found. When I click on Options->Kits, I see the Desktop (default) kit, and it shows no errors.
Am I getting the error because I didn’t install a Qt library? If so, is there any way I can bypass downloading/installing that and just use the IDE?
Found the issue. Qt Creator wants you to use a compiler listed under one of their Qt libraries. Use the Maintenance Tool to install this.
To do so:
Go to Tools -> Options…. Select Build & Run on left. Open Kits tab. You should have Manual -> Desktop (default) line in list. Choose it. Now select something like Qt 5.5.1 in PATH (qt5) in Qt version combobox and click Apply button. From now you should be able to create, build and run empty Qt project.
Though OP is asking about Windows, this error also occurs on Ubuntu Linux and Google lists this result first when you search for the error“QtCreator: No valid kits found”.
On Ubuntu this is solved by running:
For Qt5:
For Qt4:
This question is answered here and here, though those entries are less SEO-friendly…
For QT 5.* if you face error at Kits, like No Valid Kits Found
, go to Options->Build&Run-> (Kits tab) then you see a Manual category which should list Desktop as the default.
Just go to your OS Terminal and write sudo apt-get install qt5-default
, go back to QT Creator and Start your New Project, and there you see the kit option Desktop included in the list.
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file?
Should I:
exit(EXIT_FAILURE)
QApplication::quit()
QCoreApplication::quit()
And difference between (2) and (3)?
QApplication is derived from QCoreApplication and thereby inherits quit()
which is a public slot of QCoreApplication
, so there is no difference between QApplication::quit()
and QCoreApplication::quit()
.
As we can read in the documentation of QCoreApplication::quit()
it “tells the application to exit with return code 0 (success).”. If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call QCoreApplication::exit()
because you can provide a non-zero returnCode which, by convention, indicates an error.
It is important to note that “if the event loop is not running, this function (QCoreApplication::exit()) does nothing”, so in that case you should call exit(EXIT_FAILURE)
.
You can call qApp.exit();
. I always use that and never had a problem with it.
If you application is a command line application, you might indeed want to return an exit code. It’s completely up to you what the code is.
If you’re using Qt Jambi, this should work:
I’d like to format a string for Qt label, I’m programming in C++ on Qt.
In ObjC I would write something like:
How to do something like that in Qt?
You can use QString.arg like this
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"
This method is preferred over sprintf because:
Changing the position of the string without having to change the ordering of substitution, e.g.
// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");
Or, changing the type of the arguments doesn’t require changing the format string, e.g.
// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));
As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.
One drawback though: QString::arg() doesn’t handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.
UPDATE: Examples are updated thanks to Frank Osterfeld.
UPDATE: Examples are updated thanks to alexisdm.
You can use the sprintf
method, however the arg
method is preferred as it supports unicode.
I have installed C++SDK that have Qt but when I try compiling a code linking QApplication it gives me the error:
How do I link these libraries? I searched into the directories and there is a file named QApplication.h; So I tried to link it with -I (linking the directory) but it was still giving me that error.
To start things off, the error QApplication: no such file or directory
means your compiler was not able to find this header. It is not related to the linking process as you mentioned in the question.
The -I
flag (uppercase i) is used to specify the include (headers) directory (which is what you need to do), while the -L
flag is used to specify the libraries directory. The -l
flag (lowercase L) is used to link your application with a specified library.
But you can use Qt to your advantage: Qt has a build system named qmake which makes things easier. For instance, when I want to compile main.cpp I create a main.pro file. For educational purposes, let’s say this source code is a simple project that uses only QApplication
and QDeclarativeView
. An appropriate .pro file would be:
Then, execute the qmake
inside that directory to create the Makefile that will be used to compile your application, and finally execute make
to get the job done.
On my system this make
outputs:
g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_DECLARATIVE_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/opt/qt_47x/mkspecs/linux-g++ -I. -I/opt/qt_47x/include/QtCore -I/opt/qt_47x/include/QtGui -I/opt/qt_47x/include/QtDeclarative -I/opt/qt_47x/include -I/usr/X11R6/include -I. -o main.o main.cpp
g++ -Wl,-O1 -Wl,-rpath,/opt/qt_47x/lib -o main main.o -L/opt/qt_47x/lib -L/usr/X11R6/lib -lQtDeclarative -L/opt/qt_47x/lib -lQtScript -lQtSvg -L/usr/X11R6/lib -lQtSql -lQtXmlPatterns -lQtNetwork -lQtGui -lQtCore -lpthread
Note: I installed Qt in another directory –> /opt/qt_47x
Edit: Qt 5.x and later
Add QT += widgets
to the .pro file and solve this problem.
In Qt 5 you now have to add widgets
to the QT
qmake variable (in your MyProject.pro
file).
For QT 5
Step1: .pro
(in pro file, add these 2 lines)
Step2: In main.cpp
replace code:
with:
In Qt, how do I check if a given folder exists in the current directory?
If it doesn’t exist, how do I then create an empty folder?
To check if a directory named “Folder” exists use:
To create a new folder named “MyFolder” use:
To both check if it exists and create if it doesn’t, including intermediaries:
When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.
You can see more on Qt Documentation
I am new to Qt, and I am trying to create a simple GUI Application that displays an image once a button has been clicked on.
I can read the image in a QImage
object, but is there any simple way to call a Qt function that takes the QImage
as an input, and displays it?
Thanks All, I found how to do it, which is the same as Dave and Sergey:
I am using QT Creator:
In the main GUI window create using the drag drop GUI and create label (e.g. “myLabel”)
In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:
Simple, but complete example showing how to display QImage might look like this:
Drawing an image using a QLabel
seems like a bit of a kludge to me. With newer versions of Qt you can use a QGraphicsView
widget. In Qt Creator, drag a Graphics View
widget onto your UI and name it something (it is named mainImage
in the code below). In mainwindow.h
, add something like the following as private
variables to your MainWindow
class:
Then just edit mainwindow.cpp
and make the constructor something like this:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
image.load("myimage.png");
scene = new QGraphicsScene(this);
scene->addPixmap(image);
scene->setSceneRect(image.rect());
ui->mainImage->setScene(scene);
}
What is the correct interpretation of the following segfault messages?
segfault at 10 ip 00007f9bebcca90d sp 00007fffb62705f0 error 4 in libQtWebKit.so.4.5.2[7f9beb83a000+f6f000]
segfault at 10 ip 00007fa44d78890d sp 00007fff43f6b720 error 4 in libQtWebKit.so.4.5.2[7fa44d2f8000+f6f000]
segfault at 11 ip 00007f2b0022acee sp 00007fff368ea610 error 4 in libQtWebKit.so.4.5.2[7f2aff9f7000+f6f000]
segfault at 11 ip 00007f24b21adcee sp 00007fff7379ded0 error 4 in libQtWebKit.so.4.5.2[7f24b197a000+f6f000]
This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).
Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d
(and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.
You’re hosed, unfortunately; it’s not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb
.
Here’s the breakdown of the fields:
address
(after the at
) - the location in memory the code is trying to access (it’s likely that 10
and 11
are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0
)
ip
- instruction pointer, ie. where the code which is trying to do this lives
sp
- stack pointer
error
- An error code for page faults; see below for what this means on x86.
/*
* Page fault error code bits:
*
* bit 0 == 0: no page found 1: protection fault
* bit 1 == 0: read access 1: write access
* bit 2 == 0: kernel-mode access 1: user-mode access
* bit 3 == 1: use of reserved bit detected
* bit 4 == 1: fault was an instruction fetch
*/
```</li>
</ul>
#### Answer 2 (score 46)
Error 4 means "The cause was a user-mode read resulting in no page being found.". There's a tool that decodes it <a href="http://rgeissert.blogspot.com/p/segmentation-fault-error.html" rel="noreferrer">here</a>.
Here's the definition from the kernel. Keep in mind that 4 means that bit 2 is set and no other bits are set. If you convert it to binary that becomes clear.
```c
/*
* Page fault error code bits
* bit 0 == 0 means no page found, 1 means protection fault
* bit 1 == 0 means read, 1 means write
* bit 2 == 0 means kernel, 1 means user-mode
* bit 3 == 1 means use of reserved bit detected
* bit 4 == 1 means fault was an instruction fetch
*/
#define PF_PROT (1<<0)
#define PF_WRITE (1<<1)
#define PF_USER (1<<2)
#define PF_RSVD (1<<3)
#define PF_INSTR (1<<4)
Now then, “ip 00007f9bebcca90d” means the instruction pointer was at 0x00007f9bebcca90d when the segfault happened.
“libQtWebKit.so.4.5.2[7f9beb83a000+f6f000]” tells you:
If you take the base address and subtract it from the ip, you get the offset into that object:
Then you can run addr2line on it:
In my case it wasn’t successful, either the copy I installed isn’t identical to yours, or it’s stripped.
Let’s go to the source – 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.
“error” is not an errno nor a signal number, it’s a “page fault error code” – see definition of enum x86_pf_error_code.
“[7fa44d2f8000+f6f000]” is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of “ip” should fit in this region. With this info in hand, it should be easy to find offending code in gdb.
I’m trying to get the current time as TimeStamp without success.
I have this code:
QDateTime setTime = QDateTime::fromString (QString("1970-07-18T14:15:09"), Qt::ISODate);
QDateTime current = QDateTime::currentDateTime();
uint msecs = setTime.time().msecsTo(current.time());
return QString::number(msecs);
The output is
I think you are looking for this function:
http://doc.qt.io/qt-5/qdatetime.html#toTime_t
uint QDateTime::toTime_t () const
Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).
On systems that do not support time zones, this function will behave as if local time were Qt::UTC.
See also setTime_t().
In Qt 4.7, there is the QDateTime::currentMSecsSinceEpoch()
static function, which does exactly what you need, without any intermediary steps. Hence I’d recommend that for projects using Qt 4.7 or newer.
Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch()
to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.
Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.
So if I go into QtDesigner and build a UI, it’ll be saved as a .ui file. How can I make this as a python file or use this in python?
Another way to use .ui in your code is:
from PyQt4 import QtCore, QtGui, uic
class MyWidget(QtGui.QWidget)
...
#somewhere in constructor:
uic.loadUi('MyWidget.ui', self)
both approaches are good. Do not forget, that if you use Qt resource files (extremely useful) for icons and so on, you must compile it too:
Note, when uic
compiles interface, it adds ‘import images_rc’ at the end of .py file, so you must compile resources into the file with this name, or rename it in generated code.
Combining Max’s answer and Shriramana Sharma’s mailing list post, I built a small working example for loading a mywindow.ui
file containing a QMainWindow
(so just choose to create a Main Window in Qt Designer’s File-New
dialog).
This is the code that loads it:
You need to generate a python file from your ui file with the pyuic tool (site-packages)
with pyqt4
Then you can import the form1 into your script.
I have this function in my program that converts integers to strings:
But when ever i run this i get the error:
Im not really sure what that means. But if you know how to fix it or need any more code please just comment. Thanks.
You probably have a forward declaration of the class, but haven’t included the header:
Like it’s written up there, you forget to type #include <sstream>
#include <sstream>
using namespace std;
QString Stats_Manager::convertInt(int num)
{
stringstream ss;
ss << num;
return ss.str();
}
You can also use some other ways to convert int
to string
, like
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
check this!
I have a Qt GUI application running on Windows that allows command-line options to be passed and under some circumstances I want to output a message to the console and then quit, for example:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if (someCommandLineParam)
{
std::cout << "Hello, world!";
return 0;
}
MainWindow w;
w.show();
return a.exec();
}
However, the console messages do not appear when I run the app from a command-prompt. Does anyone know how I can get this to work?
Windows does not really support dual mode applications.
To see console output you need to create a console application
However, if you double click on the program to start the GUI mode version then you will get a console window appearing, which is probably not what you want. To prevent the console window appearing you have to create a GUI mode application in which case you get no output in the console.
One idea may be to create a second small application which is a console application and provides the output. This can call the second one to do the work.
Or you could put all the functionality in a DLL then create two versions of the .exe file which have very simple main functions which call into the DLL. One is for the GUI and one is for the console.
Add:
#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
#endif
at the top of main()
. This will enable output to the console only if the program is started in a console, and won’t pop up a console window in other situations. If you want to create a console window to display messages when you run the app outside a console you can change the condition to:
void Console()
{
AllocConsole();
FILE *pFileCon = NULL;
pFileCon = freopen("CONOUT$", "w", stdout);
COORD coordInfo;
coordInfo.X = 130;
coordInfo.Y = 9000;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coordInfo);
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),ENABLE_QUICK_EDIT_MODE| ENABLE_EXTENDED_FLAGS);
}
int main(int argc, char *argv[])
{
Console();
std::cout<<"start@@";
qDebug()<<"start!";
You can’t use std::cout as others have said,my way is perfect even for some code can’t include “qdebug” !
I was trying to create a simple console application to try out Qt’s XML parser. I started a project in VS2008 and got this template:
Since I don’t need event processing, I was wondering whether I may get into trouble if I neglect to create a QCoreApplication and running the event loop. The docs state that it’s recommended in most cases.
For the sake of curiosity however, I am wondering how could I make some generic task execute on the event loop and then terminate the application. I was unable to google a relevant example.
Here is one simple way you could structure an application if you want an event loop running.
// main.cpp
#include <QtCore>
class Task : public QObject
{
Q_OBJECT
public:
Task(QObject *parent = 0) : QObject(parent) {}
public slots:
void run()
{
// Do processing here
emit finished();
}
signals:
void finished();
};
#include "main.moc"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Task parented to the application so that it
// will be deleted by the application.
Task *task = new Task(&a);
// This will cause the application to exit when
// the task signals finished.
QObject::connect(task, SIGNAL(finished()), &a, SLOT(quit()));
// This will run the task from the application event loop.
QTimer::singleShot(0, task, SLOT(run()));
return a.exec();
}
Don’t forget to add the
flag in the qmake .pro file.
For the rest is just using some of Qt classes. One way I use it is to spawn processes cross-platform.
You don’t need the QCoreApplication
at all, just include your Qt objects as you would other objects, for example:
#include <QtCore>
int main()
{
QVector<int> a; // Qt object
for (int i=0; i<10; i++)
{
a.append(i);
}
/* manipulate a here */
return 0;
}
I have a Qt project and I would like to output compilation files outside the source tree.
I currently have the following directory structure:
Depending on the configuration (debug/release), I will like to output the resulting files inside the build directory under build/debug or build/release directories.
How can I do that using a .pro file?
The short answer is: you don’t.
You should run qmake
followed by make
in whatever build directory you want to build in. So, run it once in a debug
directory, once in a release
directory.
That’s how anyone building your project would expect it to work, and that’s how Qt itself is set up to build, that’s also how Qt Creator expects your .pro
file to behave: it simply starts qmake
and then make
in the build folder for your target’s chosen configuration.
If you wish to create these folders and perform the two (or more) builds in them, you’ll need a top-level makefile, possibly created from a top-level project file via qmake.
It’s not uncommon to have more than two build configurations, so you’re unnecessarily committing yourself to only differentiating between a build and a release; you might have builds with different optimization levels, etc. The debug/release dichotomy is best left to rest in peace.
For my Qt project, I use this scheme in *.pro file:
HEADERS += src/dialogs.h
SOURCES += src/main.cpp \
src/dialogs.cpp
Release:DESTDIR = release
Release:OBJECTS_DIR = release/.obj
Release:MOC_DIR = release/.moc
Release:RCC_DIR = release/.rcc
Release:UI_DIR = release/.ui
Debug:DESTDIR = debug
Debug:OBJECTS_DIR = debug/.obj
Debug:MOC_DIR = debug/.moc
Debug:RCC_DIR = debug/.rcc
Debug:UI_DIR = debug/.ui
It`s simple, but nice! :)
To change the directory for target dll/exe, use this in your pro file:
You might also want to change directories for other build targets like object files and moc files (check qmake variable reference for details or qmake CONFIG() function reference).
Platform: QT, Windows XP
I am new to Qt. I want to show another window(what to do to open it as dialog) from mainwindow
. I did “add New Item ->Qt Designer Form Class
”, named it say MyWindow
. But how to show this MyWindow
from mainwindow
?
click()
to the QMainWindow custom slot you have created).
Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
void openNewWindow();
// ...
private:
NewWindow *mMyNewWindow;
// ...
}
MainWindow.cpp
// ...
MainWindow::MainWindow()
{
// ...
connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
// ...
}
// ...
void MainWindow::openNewWindow()
{
mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
mMyNewWindow->show();
// ...
}
This is an example on how display a custom new window. There are a lot of ways to do this.
In my application I want that when a loop is being executed, each time the control transfers to the loop, each execution must be delayed by a particular time. How can I do this?
EDIT (removed wrong solution). EDIT (to add this other option):
Another way to use it would be subclass QThread since it has protected *sleep methods.
QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);
Here’s the code to create your own *sleep method.
#include <QThread>
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
and you call it by doing this:
This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.
As an update of @Live’s answer, for Qt ≥ 5.2 there is no more need to subclass QThread
, as now the sleep functions are public:
Static Public Members
QThread * currentThread()
Qt::HANDLE currentThreadId()
int idealThreadCount()
void msleep(unsigned long msecs)
void sleep(unsigned long secs)
void usleep(unsigned long usecs)
void yieldCurrentThread()
cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members
C++11 has some portable timer stuff. Check out sleep_for.
I am writing a program in QT. I want to convert a double
into a Qstring
in C++.
Use QString’s number method (docs are here):
Instead of QString::number()
i would use QLocale::toString()
, so i can get locale aware group seperatores like german “1.234.567,89”.
You can use arg(), as follow:
This overcomes the problem of: “Fixed precision” at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision
How to change the title of the window in Qt? (Both for QDialog
and QMainWindow
.)
EDIT: If you are using QtDesigner, on the property tab, there is an editable property called windowTitle which can be found under the QWidget section. The property tab can usually be found on the lower right part of the designer window.
For new Qt users this is a little more confusing than it seems if you are using QT Designer and .ui
files.
Initially I tried to use ui->setWindowTitle
, but that doesn’t exist. ui
is not a QDialog
or a QMainWindow
.
The owner of the ui
is the QDialog
or QMainWindow
, the .ui
just describes how to lay it out. In that case, you would use:
I hope this helps someone else.
I know this is years later but I ran into the same problem. The solution I found was to change the window title in main.cpp. I guess once the w.show();
is called the window title can no longer be changed. In my case I just wanted the title to reflect the current directory and it works.
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle(QDir::currentPath());
w.show();
return a.exec();
}
Compiling on Fedora 10.
I have just started my first qt GUI application. I used all the default settings.
Its just a simple form. It builds OK without any errors. But when I try and run the application. I get the following message:
Starting /home/rob/projects/qt/test1/test1/test1...
No protocol specified
test1: cannot connect to X server :0.0
Thanks for any advice,
The general causes for this are as follows:
DISPLAY not set in the environment.
Solution:
Non-Authorised User trying to run the X Application
Solution ( as X owning user, ie: yourself )
xhost +local:root # where root is the local user you want to grant access to.
```</li>
</ol>
#### Answer 2 (score 5)
Also, if you'd like your X server to be able to receive connection over TCP, these days you must almost always explicitly enable this. To test whether you're server is allowing remote TCP connections try:
telnet 127.0.0.1 6000
If telnet is able to connect, then your X server is listening. If it can't, then neither will any remote X application and you need to enable remote TCP connections on your server.
#### Answer 3 (score 2)
<p>Adding to above answers.
I was in a similar situation while running tests for <a href="https://github.com/tushar-rishav/code2pdf" rel="nofollow">Code2Pdf</a> at travis.
I solved the problem using <a href="http://manpages.ubuntu.com/manpages/lucid/man1/xvfb-run.1.html" rel="nofollow">xvfb-run</a>. Quoting from the manpage,</p>
<blockquote>
xvfb-run is a wrapper for the Xvfb(1x) command which simplifies the task of running commands (typically an X client, or a script containing a list of clients to be run) within a virtual X server environment.
</blockquote>
The script that I wrote was:
```c
check_install_xvfb() { # check and install xvfb
if hash xvfb-run 2>/dev/null; then
:
else
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install xvfb
fi
}
check_install_xvfb
export DISPLAY=localhost:1.0
xvfb-run -a bash .misc/tests.sh
# .misc/tests.sh is script that runs unit tests. You can replace it with something suitable to you.
Please bear with my bash code style. I am a noob bash programmer.
Running the above script helped me. You can see the failing build and passing build.
Hope it helps
Which is better (or faster), a C++ for
loop or the foreach
operator provided by Qt? For example, the following condition
Which is better?
or
It really doesn’t matter in most cases.
The large number of questions on StackOverflow regarding whether this method or that method is faster, belie the fact that, in the vast majority of cases, code spends most of its time sitting around waiting for users to do something.
If you are really concerned, profile it for yourself and act on what you find.
But I think you’ll most likely find that only in the most intense data-processing-heavy work does this question matter. The difference may well be only a couple of seconds and even then, only when processing huge numbers of elements.
Get your code working first. Then get it working fast (and only if you find an actual performance issue).
Time spent optimising before you’ve finished the functionality and can properly profile, is mostly wasted time.
First off, I’d just like to say I agree with Pax, and that the speed probably doesn’t enter into it. foreach wins hands down based on readability, and that’s enough in 98% of cases.
But of course the Qt guys have looked into it and actually done some profiling: http://blog.qt.io/blog/2009/01/23/iterating-efficiently/
The main lesson to take away from that is: use const references in read only loops as it avoids the creation of temporary instances. It also make the purpose of the loop more explicit, regardless of the looping method you use.
It really doesn’t matter. Odds are if your program is slow, this isn’t the problem. However, it should be noted that you aren’t make a completely equal comparison. Qt’s foreach
is more similar to this (this example will use QList<QString>
):
for(QList<QString>::iterator it = Con.begin(); it != Con.end(); ++it) {
QString &str = *it;
// your code here
}
The macro is able to do this by using some compiler extensions (like GCC’s __typeof__
) to get the type of the container passed. Also imagine that boost’s BOOST_FOREACH
is very similar in concept.
The reason why your example isn’t fair is that your non-Qt version is adding extra work.
You are indexing instead of really iterating. If you are using a type with non-contiguous allocation (I suspect this might be the case with QList<>
), then indexing will be more expensive since the code has to calculate “where” the n-th item is.
That being said. It still doesn’t matter. The timing difference between those two pieces of code will be negligible if existent at all. Don’t waste your time worrying about it. Write whichever you find more clear and understandable.
EDIT: As a bonus, currently I strongly favor the C++11 version of container iteration, it is clean, concise and simple:
This question must be duplicate many times, but it just doesn’t work and sometimes it still remains unanswered. Sources of information are mainly these
http://www.laganiere.name/opencvCookbook/chap1s1_2.shtml
http://www.youtube.com/watch?v=dgcXYQijV6c
This is the summation of what I think one should/can do. (And now it works for me.) Hopefully I mentioned everything from the very beginning, the aim is to write a very clear tutorial.
Installation of OpenCV for QtCreator
Now I have created a new console app in QtCreator.
//cvHello.pro
QT += core
QT -= gui
TARGET = cvHello
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
INCLUDEPATH += C:/Programs/opencv24/opencv_bin2/install/include
LIBS += "C:/Programs/opencv24/opencv_bin2/bin/*.dll"
SOURCES += main.cpp
OTHER_FILES += \
img.JPG
And the main file:
//main.cpp
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"
using namespace std;
int main()
{
cout << "Hello World!" << endl;
cv::Mat mat;
mat = cv::imread("img.JPG");
cvNamedWindow("hello");
cv::imshow("hello",mat);
cvWaitKey(0);
return 0;
}
Finally I am starting to be happy. When adjusting this question I had to try all ways, how to define LIBS. Listing them manually helped, at first I wrote them somehow wrongly.
This is how it works finally:
LIBS += -LC:\\Programs\\opencv24\\opencv_bin2\\bin \
libopencv_core240d \
libopencv_highgui240d \
libopencv_imgproc240d \
libopencv_features2d240d \
libopencv_calib3d240d \
Btw if I’ve made any grammar mistakes, I am sorry for my english. :)
The originally accepted answer did not work for me, I am running MSVC2013 Professional and QT5.9. I found SIMPLE and SUREFIRE CROSS-PLATFORM solution that should help anyone who is trying to link an external library (like openCV) with QT.
The steps listed below are found in the Qt5 documentation: http://doc.qt.io/qtcreator/creator-project-qmake-libraries.html under the “To Add Library” section.
Let me add some specificity from here:
I’m having issues with QByteArray
and QString
.
I’m reading a file and stores its information in a QByteArray
. The file is in unicode, so it contains something like: t\0 e\0 s\0 t\0 \0 \0
I’m trying to compare this value to my specified value, but it fails, because in the debugger I see it’s not an unicode string.
The code will explain everything:
QByteArray Data; //contains unicode string "t\0 e\0 s\0 t\0 \0 \0"
QString myValue = "test"; //value to compare.
if(Data.contains(myValue))
//do some stuff.
else
//do other stuff.
In the debugger, it shows me that the variable Data
has the value "t\0 e\0 s\0 t\0 \0 \0"
and myValue
has the value "test"
. How can I fix it?
You can use QTextCodec to convert the bytearray to a string:
(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)
From your example we can see that the string "test"
is encoded as "t\0 e\0 s\0 t\0 \0 \0"
in your encoding, i.e. every ascii character is followed by a \0
-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).
you can use QString::fromAscii()
with data()
returning a char*
for QT5, you should use fromCString()
instead, as fromAscii()
is deprecated, see https://bugreports.qt-project.org/browse/QTBUG-21872 https://bugreports.qt.io/browse/QTBUG-21872
You can use:
How can I read a text file line by line in Qt?
I’m looking for the Qt equivalent to:
Use this code:
Since Qt 5.5 you can use QTextStream::readLineInto
. It behaves similar to std::getline
and is maybe faster as QTextStream::readLine
, because it reuses the string:
In Qt I’m trying to set a QTimer
that calls a function called “update” every second. Here is my .cpp file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include "QDebug"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::update()
{
qDebug() << "update";
}
and the main:
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
The project is being build, but it doesn’t execute update, since the line “update” is not showing anywhere… Does anybody see what I´m doing wrong?
It’s good practice to give a parent to your QTimer
to use Qt’s memory management system.
update()
is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.
If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.
Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.
Other way is using of built-in method start timer & event TimerEvent.
Header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
int timerId;
protected:
void timerEvent(QTimerEvent *event);
};
#endif // MAINWINDOW_H
Source:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timerId = startTimer(1000);
}
MainWindow::~MainWindow()
{
killTimer(timerId);
delete ui;
}
void MainWindow::timerEvent(QTimerEvent *event)
{
qDebug() << "Update...";
}
mytimer.h:
#ifndef MYTIMER_H
#define MYTIMER_H
#include <QTimer>
class MyTimer : public QObject
{
Q_OBJECT
public:
MyTimer();
QTimer *timer;
public slots:
void MyTimerSlot();
};
#endif // MYTIME
mytimer.cpp:
#include "mytimer.h"
#include <QDebug>
MyTimer::MyTimer()
{
// create a timer
timer = new QTimer(this);
// setup signal and slot
connect(timer, SIGNAL(timeout()),
this, SLOT(MyTimerSlot()));
// msec
timer->start(1000);
}
void MyTimer::MyTimerSlot()
{
qDebug() << "Timer...";
}
main.cpp:
#include <QCoreApplication>
#include "mytimer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Create MyTimer instance
// QTimer object will be created in the MyTimer constructor
MyTimer timer;
return a.exec();
}
If we run the code:
I have a Qt application, and when I run this application, there is a console opening behind it. In development it is nice because i see debug outputs on the console, but when I want to give this executable to the customer there should be no console window. how do I hide it?
(I am using Visual Studio 2008)
It sounds like your linker configuration is incorrect. Right-click the project, Properties, Linker, System, SubSystem setting. Make sure “Windows” is selected, not “Console”.
And, change main() to WinMain().
In the project build linker options set
Or use the following #pragma in the source file with the int main(...)
You can get rid of the console by calling:
Qt5 has a new JSon parser and I want to use it. The problem is that it isn’t too clear about what the functions do in layman’s terms and how to write code with it. That or I could be reading it wrong.
I want to know the code on creating a Json file in Qt5 and what “encapsulates” mean.
Example: Read json from file
/* test.json */
{
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}
void readJson()
{
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonValue value = sett2.value(QString("appName"));
qWarning() << value;
QJsonObject item = value.toObject();
qWarning() << tr("QJsonObject of description: ") << item;
/* in case of string value get value and convert into string*/
qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
QJsonValue subobj = item["description"];
qWarning() << subobj.toString();
/* in case of array get array and convert into string*/
qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
QJsonArray test = item["imp"].toArray();
qWarning() << test[1].toString();
}
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
Example: Read json from string
Assign json to string as below and use the readJson()
function shown before:
val =
' {
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}';
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.
So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:
value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;
and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL
as needed):
value x(ctx);
std::cin >> x;
if (x.soap->error)
exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
if (x["appDesc"].has("description"))
USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
if (x["appDesc"].has("message"))
USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
if (x["appName"].has("description"))
USE_VAL("$.appName.description", x["appName"]["description"]);
if (x["appName"].has("message"))
USE_VAL("$.appName.message", x["appName"]["message"]);
if (x["appName"].has("imp"))
{
for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
}
}
This code uses the JSON C++ API of gSOAP 2.8.28. I don’t expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.
An example on how to use that would be great. There is a couple of examples at the Qt forum, but you’re right that the official documentation should be expanded.
QJsonDocument
on its own indeed doesn’t produce anything, you will have to add the data to it. That’s done through the QJsonObject
, QJsonArray
and QJsonValue
classes. The top-level item needs to be either an array or an object (because 1
is not a valid json document, while {foo: 1}
is.)
I’m looking for the equivalent in Qt to GetTickCount()
Something that will allow me to measure the time it takes for a segment of code to run as in:
any suggestions?
How about QTime
? Depending on your platform it should have 1 millisecond accuracy. Code would look something like this:
I think it’s probably better to use QElapsedTimer
since that is why the class exists in the first place. It was introduced with Qt 4.7. Note that it is also immuned to system’s clock time change.
Example usage:
Even if the first answer was accepted, the rest of the people who read the answers should consider sivabudh
’s suggestion.
QElapsedTimer
can also be used to calculate the time in nanoseconds.
Code example:
QElapsedTimer timer;
qint64 nanoSec;
timer.start();
//something happens here
nanoSec = timer.nsecsElapsed();
//printing the result(nanoSec)
//something else happening here
timer.restart();
//some other operation
nanoSec = timer.nsecsElapsed();
What would be the best way of selecting an item in a QT combo box out of a predefined list of enum
based unique values.
In the past I have become accustomed to .NET’s style of selection where the item can be selected by setting the selected property to the item’s value you wish to select:
Is there anyway to do this with QT based on the item’s data, if the data is a C++ enumeration?
You lookup the value of the data with findData()
and then use setCurrentIndex()
You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don’t need to set the second parameter when you add an item.
Here is a little example :
/* Create the comboBox */
QComboBox *_comboBox = new QComboBox;
/* Create the ComboBox elements list (here we use QString) */
QList<QString> stringsList;
stringsList.append("Text1");
stringsList.append("Text3");
stringsList.append("Text4");
stringsList.append("Text2");
stringsList.append("Text5");
/* Populate the comboBox */
_comboBox->addItems(stringsList);
/* Create the label */
QLabel *label = new QLabel;
/* Search for "Text2" text */
int index = _comboBox->findText("Text2");
if( index == -1 )
label->setText("Text2 not found !");
else
label->setText(QString("Text2's index is ")
.append(QString::number(_comboBox->findText("Text2"))));
/* setup layout */
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(_comboBox);
layout->addWidget(label);
If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.
From the Qt 5.7 documentation
The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.
So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.
Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop
I use a QLabel to display the content of a bigger, dynamically changing QPixmap to the user. It would be nice to make this label smaller/larger depending on the space available. The screen size is not always as big as the QPixmap.
How can I modify the QSizePolicy
and sizeHint()
of the QLabel to resize the QPixmap while keeping the aspect ratio of the original QPixmap?
I can’t modify sizeHint()
of the QLabel, setting the minimumSize()
to zero does not help. Setting hasScaledContents()
on the QLabel allows growing, but breaks the aspect ratio thingy…
Subclassing QLabel did help, but this solution adds too much code for just a simple problem…
Any smart hints how to accomplish this without subclassing?
In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.
You can scale the pixmap by keeping its aspect ratio every time it changes:
QPixmap p; // load pixmap
// get label dimensions
int w = label->width();
int h = label->height();
// set a scaled pixmap to a w x h window keeping its aspect ratio
label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio));
There are two places where you should add this code:
resizeEvent
of the widget that contains the label
I have polished this missing subclass of QLabel
. It is awesome and works well.
aspectratiopixmaplabel.h
#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H
#include <QLabel>
#include <QPixmap>
#include <QResizeEvent>
class AspectRatioPixmapLabel : public QLabel
{
Q_OBJECT
public:
explicit AspectRatioPixmapLabel(QWidget *parent = 0);
virtual int heightForWidth( int width ) const;
virtual QSize sizeHint() const;
QPixmap scaledPixmap() const;
public slots:
void setPixmap ( const QPixmap & );
void resizeEvent(QResizeEvent *);
private:
QPixmap pix;
};
#endif // ASPECTRATIOPIXMAPLABEL_H
aspectratiopixmaplabel.cpp
#include "aspectratiopixmaplabel.h"
//#include <QDebug>
AspectRatioPixmapLabel::AspectRatioPixmapLabel(QWidget *parent) :
QLabel(parent)
{
this->setMinimumSize(1,1);
setScaledContents(false);
}
void AspectRatioPixmapLabel::setPixmap ( const QPixmap & p)
{
pix = p;
QLabel::setPixmap(scaledPixmap());
}
int AspectRatioPixmapLabel::heightForWidth( int width ) const
{
return pix.isNull() ? this->height() : ((qreal)pix.height()*width)/pix.width();
}
QSize AspectRatioPixmapLabel::sizeHint() const
{
int w = this->width();
return QSize( w, heightForWidth(w) );
}
QPixmap AspectRatioPixmapLabel::scaledPixmap() const
{
return pix.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
void AspectRatioPixmapLabel::resizeEvent(QResizeEvent * e)
{
if(!pix.isNull())
QLabel::setPixmap(scaledPixmap());
}
Hope that helps! (Updated resizeEvent
, per @dmzl’s answer)
I just use contentsMargin
to fix the aspect ratio.
#pragma once
#include <QLabel>
class AspectRatioLabel : public QLabel
{
public:
explicit AspectRatioLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
~AspectRatioLabel();
public slots:
void setPixmap(const QPixmap& pm);
protected:
void resizeEvent(QResizeEvent* event) override;
private:
void updateMargins();
int pixmapWidth = 0;
int pixmapHeight = 0;
};
#include "AspectRatioLabel.h"
AspectRatioLabel::AspectRatioLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f)
{
}
AspectRatioLabel::~AspectRatioLabel()
{
}
void AspectRatioLabel::setPixmap(const QPixmap& pm)
{
pixmapWidth = pm.width();
pixmapHeight = pm.height();
updateMargins();
QLabel::setPixmap(pm);
}
void AspectRatioLabel::resizeEvent(QResizeEvent* event)
{
updateMargins();
QLabel::resizeEvent(event);
}
void AspectRatioLabel::updateMargins()
{
if (pixmapWidth <= 0 || pixmapHeight <= 0)
return;
int w = this->width();
int h = this->height();
if (w <= 0 || h <= 0)
return;
if (w * pixmapHeight > h * pixmapWidth)
{
int m = (w - (pixmapWidth * h / pixmapHeight)) / 2;
setContentsMargins(m, 0, m, 0);
}
else
{
int m = (h - (pixmapHeight * w / pixmapWidth)) / 2;
setContentsMargins(0, m, 0, m);
}
}
Works perfectly for me so far. You’re welcome.
I am trying to set the background color for a double spin box, and I am not sure what function I should use.
I saw some function called SetBackgroundRole
which accepts a Qt::ColorRole
, but I am not sure how to use this one as well.
Kindly let me know, what’s the simple way to change the background color of a QComboBox
or QDoubleSpinBox
?
Using a QPalette
isn’t guaranteed to work for all styles, because style authors are restricted by the different platforms’ guidelines and by the native theme engine.
To make sure your background color will be correct, I would suggest to use the Qt Style Sheet. Here is what I did to change the background color of a QComboBox
:
myComboBox->setStyleSheet("QComboBox { background-color: blue; }");
I haven’t specifically tried for a QSpinBox
, but I guess it’ll work the same !
fhe is generally correct, but doesn’t account for the widgets (like spin boxes and buttons/comboboxes) that use a different background role in the palette. A more general solution would be something like this:
QPalette pal = widget.palette();
pal.setColor(widget.backgroundRole(), Qt::blue);
widget.setPalette(pal);
Alternatively, you could look into the descriptions of the various palette roles and figure out the one you want, then apply it to the widget containing the others you want changed. The palette changes should propagate to the children widgets.
Actually, if you look at the Qt docs for QPalette in the case of a QComboBox the background role is probably not what you want. What you want is:
QPalette::Base Used mostly as the background color for text entry widgets, but can also be used for other painting - such as the background of combobox drop down lists and toolbar handles. It is usually white or another light color.
So here is the code I am using to set the background color of a combo box I am using to match the color of the widget it is on:
QPalette pal = myComboBox->palette();
pal.setColor(QPalette::Base, pal.color(QPalette::Window));
myComboBox->setPalette(pal);
I am new to Android Studio and I am having problems while using the emulator. When I try to run it keeps crashing saying:
“Cannot launch AVD in emulator” [6816]:ERROR:./android/qt/qt_setup.cpp:28:Qt library not found at C:
Could not launch ‘C:/qemu/windows-x86_64/qemu-system-i386.exe’: No such file or directory
I have enabled VT-x from BIOS settings yet I am having the problem. I have searched a lot and cannot find an answer. Any help will be much appreciated. Can anyone give me a solution?
This seems to be an issue relating to the recent update. A temporary solution is to launch emulator from within the /path/to/android-sdk/tools
directory in the commandline.
See https://code.google.com/p/android/issues/detail?id=235461 to follow the issue.
All other answers did not work for me as “Android Emulator” was not installed with a standard installation of Android Studio. Make sure you have installed it and then try other answers if required.
I have a QLineEdit
where the user should input only numbers.
So is there a numbers-only setting for QLineEdit
?
QLineEdit::setValidator()
, for example:
or
See: QIntValidator, QDoubleValidator, QLineEdit::setValidator
The best is QSpinBox
.
And for a double value use QDoubleSpinBox
.
QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));
Why don’t you use a QSpinBox
for this purpose ? You can set the up/down buttons invisible with the following line of codes:
// ...
QSpinBox* spinBox = new QSpinBox( this );
spinBox->setButtonSymbols( QAbstractSpinBox::NoButtons ); // After this it looks just like a QLineEdit.
//...
I Have Installed Qt Creator5 with latest binaries. but when i am running any program it is giving me this error.
:-1: error: Qt Creator needs a compiler set up to build. Configure a compiler in the kit options.
i have searched the whole internet for answer but its inadequate and not helping. kindly reply the way to get rid of this error.
i was also having the same problem so what i did is
For linux
and then closed the qt creator and restarted it and it worked
i do not know which of the above two made it work but it worked !!
For Windows
Below given solution have worked for few people. so it is worth a try.
Delete this file C:\Users\AppData\Roaming\QtProject\qtcreator\toolchains.xml
to solve the problem.
For me on Windows 7 this was solved by clicking on the arrow icon next to the computer icon on the bottom left of the Qt Creator screen above green arrows and then double clicked a compiler on the list and rebuild the project.
* for windows users only *
Before continuing to next steps make sure u have downloaded latest version of Qt.
In Compilers tab Select add -> MinGW ->
Name: MinGW
path: Browse for mingw-w64.bat (you will find this file in the directory in which you have installed MinGW).
ABI: x86 Windows msvc2015 pe 64bit
Don’t forget to apply your edits.
Go to Kit -> add
Name: GCC
Device Type: Desktop
Device: Local PC (Default for desktop)
Compiler: minGW
Qt Version: select newest version
Apply changes and restart qt
While creating new project make sure you use GCC as kit
If it still doesn’t works Click computer icon on bottom left above play button -> GCC -> Build
OR
Go to projects (It is in the menu on left hand side) -> Build Steps -> make -> Override minGw31-make.exe -> browse to path in which you have installed minGW/bin-make.exe
Do the same for clean steps too
If u Still get any error after these steps try setting Environment Variables
That should do it !!!
Qt documentation states that signals and slots can be direct
, queued
and auto
.
It also stated that if object that owns slot ‘lives’ in a thread different from object that owns signal, emitting such signal will be like posting message - signal emit will return instantly and slot method will be called in target thread’s event loop.
Unfortunately, documentation do not specify that ‘lives’ stands for and no examples is available. I have tried the following code:
main.h:
class CThread1 : public QThread
{
Q_OBJECT
public:
void run( void )
{
msleep( 200 );
std::cout << "thread 1 started" << std::endl;
MySignal();
exec();
}
signals:
void MySignal( void );
};
class CThread2 : public QThread
{
Q_OBJECT
public:
void run( void )
{
std::cout << "thread 2 started" << std::endl;
exec();
}
public slots:
void MySlot( void )
{
std::cout << "slot called" << std::endl;
}
};
main.cpp:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CThread1 oThread1;
CThread2 oThread2;
QObject::connect( & oThread1, SIGNAL( MySignal() ),
& oThread2, SLOT( MySlot() ) );
oThread1.start();
oThread2.start();
oThread1.wait();
oThread2.wait();
return a.exec();
}
Output is:
MySlot()
is never called :(. What I’m doing wrong?
There are quite a few problems with your code :
This code would most likely work (though I have not tested it) and I think it does what you want it to do :
class MyObject : public QObject
{
Q_OBJECT
public slots:
void MySlot( void )
{
std::cout << "slot called" << std::endl;
}
};
class CThread1 : public QThread
{
Q_OBJECT
public:
void run( void )
{
std::cout << "thread 1 started" << std::endl;
int i = 0;
while(1)
{
msleep( 200 );
i++;
if(i==1000)
emit MySignal();
}
}
signals:
void MySignal( void );
};
class CThread2 : public QThread
{
Q_OBJECT
public:
void run( void )
{
std::cout << "thread 2 started" << std::endl;
exec();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CThread1 oThread1;
CThread2 oThread2;
MyObject myObject;
QObject::connect( & oThread1, SIGNAL( MySignal() ),
& myObject, SLOT( MySlot() ) );
oThread2.start();
myObject.moveToThread(&oThread2)
oThread1.start();
return a.exec();
}
Now MyObject will live in thread2 (thanks to moveToThread).
MySignal should be sent from thread1 (thought I’m not sure on that one, it might be sent from main thread, it doesn’t really matter).
No event loop is needed in thread1 since emitting a signal doesn’t need an event loop. An event loop is needed in thread2 (lanched by exec()) to receive the signal.
MySlot will be called in thread2.
While Aiua’s answer is good, I want to point out some issues with QThread and Qt 4.6 or 4.7.
This article sums it up: http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/
Unfortunately the problem stems from a lack of updates to documentation. Prior to Qt 4.4 QThread had no default run() implementation, which meant that you had to subclass QThread in order to use it.
If you’re using Qt 4.6 or 4.7 then you almost certainly should not subclass QThread.
The key to getting slots to execute in a worker thread is to use the moveToThread method as Aiua pointed out.
you should emit the signal to start your thread function like
emit operateCut(examId,examName_examTemplate[examName].studentIdRec,examName_examTemplate[examName].choiceRecA,examName_examTemplate[examName].choiceRecB,examName_examTemplate[examName].objectRecA,examName_examTemplate[examName].objectRecB);
you can add more than one argument in this signal
I am trying to deploy(release to public) a simple qt application I made recently, but got stuck at static linking qt libs.
I followed the guide on qt docs to re-build qt and my app statically. But the release build still require qtgui / qtcore dll for no apparent reasons, I wonder if anyone has seen this kind of problems before ? Or even better, has successfully resolved it ?
I wrote a guide to static linking
and How to build Qt static with multiple compilers and keep it small
(because it can get pretty big, especially for simple programs). You may also want to check out the BitRock installer, which is free for open source projects.
In short, it turns out to be a little more complex if you are using anything Qt thinks of as a plugin, such as support for most image types (JPEG, GIF) or databases. For example, if you want to include support for Oracle DBMS and GIF images for your icons, you add the following to your .PRO file:
You will then need to:
in your project, and import any plugins used. You need to change these settings back order to get it to compile with dynamic linking again (like when debugging or adding features), though this can be easily automated. There are also considerations when building the Qt libraries for use with static linking, though the Qt instructions will at least get you started.
With Qt 5.5, things are quite easy. There are following orthogonal settings that you pass to configure
when building Qt:
Do you want a static Qt library?
-static
option should be passed to configure
Do you want the build of Qt, and of your application, to use a static C++ runtime?
-static-runtime
option should be passed to configure
Do you want XP targeting?
-target xp
option should be passed to configure
Additionally, follow the instructions from this blog post.
Qt Creator didn’t support XP targeting automagically at least until v.3.5.0 since it doesn’t set up the environment for the build tools properly. You have to modify the build environment manually per the blog post.
The “Browse For Folder” Windows dialog is very inconvenient because:
Is there a way to use the “Open File” dialog (which is much better) to select a Folder? Some flag or option or something?
Context: the calibre eLibrary manager which is written in Python and Qt.
It currently displays as on the left. I’d like it to display as on the right
or even better, as the Open File dialog:
You can try this one:
QString QFileDialog::getExistingDirectory ( QWidget * parent = 0, const QString & caption = QString(), const QString & dir = QString(), Options options = ShowDirsOnly ) [static]
This one is used to choose a directory, and will popup a dialog like you show at last.
Demo:
You can set the file mode in QFileDialog
to QFileDialog::Directory
see http://qt-project.org/doc/qt-5.0/qtwidgets/qfiledialog.html#FileMode-enum
Or You can use QFileDialog::setOption
with value QFileDialog::ShowDirsOnly
The question here is the same as mine but the solution there is not working for me. I am using QtCreator 2.4.1 on Windows 7. When i try to debug a simple hello world app the message displayed is: “The preferred debugger engine for debugging binaries of type ‘x86-windows-msvc2010-pe-32bit’ is not available….Details: There is no CDB binary available for binaries in format ’x86-windows-msvc2010-pe-32bit”
When i found that cdb.exe was not on my system i had Windows SDK installed with debugger tools and the current location of cdb.exe is “C:Files (x86)Kits\8.0.exe” and “C:Files (x86)Kits\8.0.exe”,
In the CDB tab i configured symbol server as well as the path of CDB.exe, but in vain!
QtCreator->Tools->options->Debugger->CDB Tab->has the following fields:
Additional arguments
use CDB console
Symbol Paths
Source Paths
Correct breakpoint location etc…
Can somebody kindly explain in detail what these mean and what values are expected here. Has anybody successfully debugged any applicaiton using Qt Creator.
Please refer this link:
http://qt-project.org/forums/viewthread/16018/
I was having the same problems too, and finally figured out how to solve this. Styne666 gave me a hint. Do the following:
I should further mention that if you are running a 64-bit version of Windows and a 32-bit version of Qt Creator like I am, you need to make sure that you are pointing to the 32-bit versions of cdb (of which there are x86 and x64 target versions). So for the 32-bit target builds I run this:
And for x64 builds I run this:
The tricky part is that it is somewhat difficult to get Microsoft to install the 32-bit version of the debugging tools on your 64-bit machine. A co-worker tried to do so recently and said that he needed to install the Windows 8 tools in order to have the option to do that - the Windows 7 versions would not let you.
Took me some time to figure out this with Qt Creator 2.6.0 (on Windows 7), so here it is:
Depending on the version of Visual Studio you have installed you can find the CDB.exe in different locations. Check if it is available in your system by searching in C: drive.
In my case I have Windows 7 (x64) with Visual Studio 2012 Express and Visual Studio 2013 installed and I had to install Microsoft Windows SDK for Windows 7 available here in order to have CDB.exe in my system. After the install, QT Creator was able to detect CDB.exe in this location: C:FilesTools for Windows (x64).exe.
The only thing you need from the SDK is the Common Utilities | Debugging Tools For Windows.
I want to ask about resources for learning Qt
for beginners. What resources do you recommend for that?
Have also a look at the Qt programming videos on VoidRealms’ Youtube channel.
The transition from C++ to QT may seem bit awkward at first. But don’t be afraid its somewhat easier than c++ when you get more familiar with it.
To start of I would like to recommend the first few videos of voidRealms youvideos on c++ QT to get a feel on QT framework. All of them are really good. Try to do the examples by your own. You will be quite comfortable with the framework after watching these videos.
Next if possible try to refer Foundations of Qt Development (Expert’s Voice in Open Source) which is also a very good reference for QT. After going through few chapters you will be very accustomed to the Framework.
Reading C++ GUI Programming with Qt 4 which is a usually recommended book will look good if you have this basic background on QT.
I would also like to recommend the On-line Reference Documentation which will give a great depth in to QT when going forward.
I’m using Code::Blocks 8.02 and the mingw 5.1.6 compiler. I’m getting this error when I compile my Qt project:
C:and Settings Fuzz_interface.cpp|33|undefined reference to `vtable for AddressBook’
File AddressBook.h:
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
class QLabel;
class QLineEdit;
class QTextEdit;
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = 0);
private:
QLineEdit *nameLine;
QTextEdit *addressText;
};
#endif
File AddressBook.cpp:
#include <QtGui>
#include "addressbook.h"
AddressBook::AddressBook(QWidget *parent)
: QWidget(parent)
{
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLine = new QLineEdit;
QLabel *addressLabel = new QLabel(tr("Address:"));
addressText = new QTextEdit;
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);
setLayout(mainLayout);
setWindowTitle(tr("Simple Address Book"));
}
Warning: Do not do this if you already have a .pro file - you’ll lose it!
In order to automatically ensure that all moc cpp files are generated, you can get qmake to automatically generate a .pro file for you instead of writing one yourself.
Run
in the project directory, and qmake will scan your directory for all C++ headers and source files to generate moc cpp files for.
When using Qt Creator:
The problem is almost certainly that you are not compiling or not linking in the generated moc_AddressBook.cpp file. (It should have been generated for you – you are running Qt’s moc
on your code before compiling, right?)
To answer a little more thoroughly, the Q_OBJECT
macro signals Qt’s moc
tool to create an extra implementation file that contains the code necessary to support QObject
’s meta-information system. If you had any signals or slots, it would do a few things for those as well.
An alternative solution might be to remove the Q_OBJECT
macro. You probably don’t want to do this, but it would help the immediate problem, and it isn’t strictly necessary with the code that you’ve presented.
Also, I would note that your line:
Should probably be:
based on how you presented the filenames in the question.
I want to “stringify” a number and add zero-padding, like how printf("%05d")
would add leading zeros if the number is less than 5 digits.
Use this:
5 here corresponds to 5 in printf("%05d")
. 10 is the radix, you can put 16 to print the number in hex.
QString QString::rightJustified ( int width, QChar fill = QLatin1Char( ’ ’ ), bool truncate = false ) const
result is now 00099
The Short Example:
int myNumber = 9;
//Arg1: the number
//Arg2: how many 0 you want?
//Arg3: The base (10 - decimal, 16 hexadecimal - if you don't understand, choose 10)
// It seems like only decimal can support negative numbers.
QString number = QString("%1").arg(myNumber, 2, 10, QChar('0'));
Output will be: 09
I just reinstalled QtCreator, created new project (Qt Application) an got this after compilation:
/usr/bin/ld: **cannot find -lGL**
collect2: error: ld returned 1 exit status
make: *** [untitled1] Error 1
18:07:41: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project untitled1 (kit: Desktop Qt 5.1.0 GCC 32bit)
When executing step 'Make'
(Project is empty, I did’n commit any changes)
Qt Creator 2.7.2
Based on Qt 5.1.0 (32 bit)
Ubuntu 13.04
How do I solve this problem?
You should install package “libgl1-mesa-dev”:
you don’t need to install anything. libGL
is already installed with Ubuntu, you just need to soft link it. (tested for ubuntu 14.x and 15.x, might work for later versions)
Here is how you could do this:
$ locate libGL
/usr/lib/i386-linux-gnu/mesa/libGL.so.1
/usr/lib/i386-linux-gnu/mesa/libGL.so.1.2.0
/usr/lib/x86_64-linux-gnu/libGLEW.so.1.10
/usr/lib/x86_64-linux-gnu/libGLEW.so.1.10.0
/usr/lib/x86_64-linux-gnu/libGLEWmx.so.1.10
/usr/lib/x86_64-linux-gnu/libGLEWmx.so.1.10.0
/usr/lib/x86_64-linux-gnu/libGLU.so.1
/usr/lib/x86_64-linux-gnu/libGLU.so.1.3.1
/usr/lib/x86_64-linux-gnu/mesa/libGL.so.1
/usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0
/usr/lib/x86_64-linux-gnu/mesa-egl/libGLESv2.so.2
/usr/lib/x86_64-linux-gnu/mesa-egl/libGLESv2.so.2.0.0
$ sudo ln -s /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1 /usr/lib/libGL.so
write:
after providing:
How do you set application icon for application made using Qt? Is there some easy way? It’s a qmake-based project.
For Qt 5, this process is automated by qmake. Just add the following to the project file:
The automated resource file generation also uses the values of the following qmake variables: VERSION, QMAKE_TARGET_COMPANY, QMAKE_TARGET_DESCRIPTION, QMAKE_TARGET_COPYRIGHT, QMAKE_TARGET_PRODUCT, RC_LANG, RC_CODEPAGE
.
For Qt 4, you need to do it manually. On Windows, you need to create a .rc file and add it to your project (.pro). The RC file should look like this:
The .pro entry should also be win32 specific, e.g.:
One more way to do that. Verified in Linux (Qt 4.8.6) and Windows (Qt 5.6):
Add the icon file to your project folder;
In the main function call setWindowIcon() method. For example:
To extend Rob’s answer, you can set an application icon for macOS by adding and modifying the following line onto your .pro
file.
Note that the ICON
qmake variable is only meant to target macOS.
For Windows, use
RC_ICONS = <app_icon>.ico
if you’re attaching a .ico
file
RC_FILE = <app_icon>.rc
if you want to attach your icon through a .rc
file. (Be sure to add IDI_ICON1 ICON DISCARDABLE "myappico.ico"
into the rc file. Indentation not mine.)
For further reading, see Setting the Application Icon.
I know some similar questions may have been asked already, but the answers to those I found covered very specific problems and I still haven’t figured it out.
In my program I’m creating a QObject (called QPeer) that uses a QTcpSocket to communicate with another such object over a network. QPeer has a slot that accepts a QByteArray with data (sendData(QByteArray)
). The entire contents of that array are considered to be one ‘message’ and they are written to the socket. I want to do the following: every time a message is written, I want the receiving QPeer to emit its signal dataReceived(QByteArray)
exactly once, that QByteArray containing the entire message. (NOTE: all signals/slots, both private ones connecting the QPeer with its socket and the public ones such as sendData(QByteArray)
are serialized by using Qt::QueuedConnection
whenever necessary.)
I use the signal QTcpSocket::readyRead()
for asynchronous reading from the socket. Now I know I can’t just call QTcpSocket::write()
once in sendData and then assume that for every write I do, the QTcpSocket on the other side produces exactly one readyRead signal. So what should I do?
This is my idea, please tell me if this will work:
WRITING:
void QPeer::sendData(QByteArray data)
{
// TODO: write data.size() as raw int of exactly 4 bytes to socket
const char *bytes = data.constData();
int bytesWritten = 0;
while (bytesWritten < data.size())
bytesWritten += _socket->write(bytes + bytesWritten);
}
READING:
now I want the read function (connected to QTcpSocket::readyRead()
) to use the header (the 4 byte int specifying the length of the message) and then read that amount of bytes; next emit dataReceived with exactly those bytes. I’m having serious trouble trying to do this. For example: what to do if readyRead is emitted and I can read the header of a message, but not the amount of bytes specified? Or what if a header has only been received partially?
1. How do I correctly write the header (4 byte int) to the socket?
2. How do I correctly implement the read function so that it does what I want?
Any tips are welcome. Thanks!
I worked on a project that does what you expect, see here the solution that I developed to our problems, simplified to be easier to understand:
Edited, added support to the server deal with multiple clients.
Client.h:
#include <QtCore>
#include <QtNetwork>
class Client : public QObject
{
Q_OBJECT
public:
explicit Client(QObject *parent = 0);
public slots:
bool connectToHost(QString host);
bool writeData(QByteArray data);
private:
QTcpSocket *socket;
};
Client.cpp:
#include "client.h"
static inline QByteArray IntToArray(qint32 source);
Client::Client(QObject *parent) : QObject(parent)
{
socket = new QTcpSocket(this);
}
bool Client::connectToHost(QString host)
{
socket->connectToHost(host, 1024);
return socket->waitForConnected();
}
bool Client::writeData(QByteArray data)
{
if(socket->state() == QAbstractSocket::ConnectedState)
{
socket->write(IntToArray(data.size())); //write size of data
socket->write(data); //write the data itself
return socket->waitForBytesWritten();
}
else
return false;
}
QByteArray IntToArray(qint32 source) //Use qint32 to ensure that the number have 4 bytes
{
//Avoid use of cast, this is the Qt way to serialize objects
QByteArray temp;
QDataStream data(&temp, QIODevice::ReadWrite);
data << source;
return temp;
}
Server.h:
#include <QtCore>
#include <QtNetwork>
class Server : public QObject
{
Q_OBJECT
public:
explicit Server(QObject *parent = 0);
signals:
void dataReceived(QByteArray);
private slots:
void newConnection();
void disconnected();
void readyRead();
private:
QTcpServer *server;
QHash<QTcpSocket*, QByteArray*> buffers; //We need a buffer to store data until block has completely received
QHash<QTcpSocket*, qint32*> sizes; //We need to store the size to verify if a block has received completely
};
Server.cpp:
#include "server.h"
static inline qint32 ArrayToInt(QByteArray source);
Server::Server(QObject *parent) : QObject(parent)
{
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), SLOT(newConnection()));
qDebug() << "Listening:" << server->listen(QHostAddress::Any, 1024);
}
void Server::newConnection()
{
while (server->hasPendingConnections())
{
QTcpSocket *socket = server->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), SLOT(readyRead()));
connect(socket, SIGNAL(disconnected()), SLOT(disconnected()));
QByteArray *buffer = new QByteArray();
qint32 *s = new qint32(0);
buffers.insert(socket, buffer);
sizes.insert(socket, s);
}
}
void Server::disconnected()
{
QTcpSocket *socket = static_cast<QTcpSocket*>(sender());
QByteArray *buffer = buffers.value(socket);
qint32 *s = sizes.value(socket);
socket->deleteLater();
delete buffer;
delete s;
}
void Server::readyRead()
{
QTcpSocket *socket = static_cast<QTcpSocket*>(sender());
QByteArray *buffer = buffers.value(socket);
qint32 *s = sizes.value(socket);
qint32 size = *s;
while (socket->bytesAvailable() > 0)
{
buffer->append(socket->readAll());
while ((size == 0 && buffer->size() >= 4) || (size > 0 && buffer->size() >= size)) //While can process data, process it
{
if (size == 0 && buffer->size() >= 4) //if size of data has received completely, then store it on our global variable
{
size = ArrayToInt(buffer->mid(0, 4));
*s = size;
buffer->remove(0, 4);
}
if (size > 0 && buffer->size() >= size) // If data has received completely, then emit our SIGNAL with the data
{
QByteArray data = buffer->mid(0, size);
buffer->remove(0, size);
size = 0;
*s = size;
emit dataReceived(data);
}
}
}
}
qint32 ArrayToInt(QByteArray source)
{
qint32 temp;
QDataStream data(&source, QIODevice::ReadWrite);
data >> temp;
return temp;
}
Note: Do not use this method to transfer large files because with this method the entire contents of the message is put inside the memory before sent and this causes a high memory usage. And because 32 bits signed INT has max value to 2,147,483,647, if your input data has a value higher than that in bytes it won’t work. Take care.
As you said, you need to wait that your header is entirely sent, before reading it, and then read the good number of bytes and emit a signal for data availability.
Here an example (untested) :
//header file
class Peer {
//[...]
protected:
bool m_headerRead; //initialize to false
unsigned int m_size_of_data_to_read;
//[...]
};
//source file
void QPeer::sendData(QByteArray data)
{
int size = data.size();
_socket->write((const char*) &size, sizeof(int);
//use directly QIODevice::write(QByteArray)
_socket->write(data);
}
void QPeer::readData()
{
int bytes = _socket->bytesAvailable();
bool contains_enough_data = true;
while (contains_enough_data) {
if (! m_headerRead && _socket->bytesAvailable() >= sizeof(int)) {
//read header only and update m_size_of_data_to_read
m_headerRead = true;
} else if (m_headerRead && _socket->bytesAvailable >= m_size_of_data_to_read) {
//read data here
m_headerRead = false;
emit dataAvailable();
} else {
contains_enough_data = false; //wait that further data arrived
}
}
}
I struggled finding a how-to which provides a stable solution for using Qt with Visual Studio 2010, so after collecting all the bits of information and some trial and error, I would like to write my solution into a guide.
It seems that using binaries built for Visual Studio 2008 might work in some special cases, but I found them not to work. In my case they compiled OK, but they produce runtime errors, like this:
or when started from Visual Studio 2010:
Update: I found a blog post analysing why does it work for some people, while it does not for others. In one word, it depends on whether you have Visual Studio 2008 installed on the same machine, or not. http://blog.paulnettleship.com/2010/11/11/troubleshooting-visual-studio-2010-and-qt-4-7-integration/
The most important thing (that I stupidly didn’t realize) was the fact that you CANNOT use the Visual Studio 2008 compiled libraries and dll’s (available on the Qt webpage) if you don’t have Visual Studio 2008 installed. The reason is because the Qt SDK you download is a debug build which is dependant on the VC9.0 DebugCRT, meaning it needs the Visual C++ 2008 Debug Runtime installed, which is NOT available as a redistributable installer. The only way to install the DebugCRT is to install the entirety of Visual Studio 2008.
First of all, it’s very important to understand that for using Qt with Visual Studio 2010, it’s not possible to use the pre-built binaries which were made for Visual Studio 2008, but you have to compile it from source.
On https://www.qt.io/download/
Update 2017: the latest Qt 4.x branch (Qt 4.8.6) has 2 pre-built packages, which are now in the archive section:
You should not download Qt by clicking “Qt libraries 4.8.6 for Windows (Visual Studio 2008, 218 MB)”, but by clicking on the “zip” link above it.
On that link, you get a big zip file like “qt-everywhere-opensource-src-4.8.6.zip”. Unzip this into a folder and make its path something nice and small, for example “E:”
Now that we have the sources, we need to build the binaries. To do it, open the Microsoft Visual Studio 2010\Visual Studio Tools\Visual Studio Command Prompt (2010)
link from your start menu, or even pin it to the taskbar (a good idea). This is a special command prompt which has all the variables set for building with Visual Studio 2010 tools.
Once within the command prompt, navigate to your extracted Qt folder using old-school DOS way, which means you have to change drive letter by E:
, enter directories by cd Qt
and list dir contents by dir
. You can use the tab key for helping you with the directory names. When you have arrived at the correct directory, a dir
command should return something like this.
Now it’s time for configure and build. For configuring a minimalist Qt, I’m using the following flags with configure.exe
. Just copy and paste it into the command line. Look in the Qt reference manual for what flag to use or not to use.
configure.exe -release -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools -no-qt3support -no-multimedia -no-ltcg
Once configure.exe
has finished (it was 10 minutes for me), you’ll need to start the build process. It will take about 20-30 minutes with the above flags. To start it, just type:
Basically, we are done. All you need to do is to set your environment variables (QTDIR
and PATH
), which tell programs where to find Qt. If you are on Windows 7, you can use the following command to set QTDIR
to your installation dir.
For setting the PATH
, I strongly recommend using Path Editor. Within Path Editor
(it doesn’t matter if it’s in system path or user path)
If you prefer to use Control Panel\System\Environment Variables
, then you can set these there, too.
Here you go, after a logoff-logon or a restart, all the Qt demo applications should start correctly (I recommend have a look at bin.exe). Now you can download and install the Visual Studio Add-in (qt-vs-addin-1.1.9.exe) from the Qt download page, it will work perfectly.
There is a page at the official wiki at the Qt website called Qt 4.8 Installing Qt for Windows, but I found it lacking important information.
Qt DevNet forums
Recommended flags for a minimalistic Qt build
Building Qt 4.5 with Visual C++ 2010
How to compile Qt as static
Qt 4.8: Configure options for Qt
Edit the PATH environment variable in
Windows without pain - op111.net
Qt V4.8.0 contains prebuilt binaries for Visual Studio 2010 so you don’t need to do this anymore: http://qt.nokia.com/downloads/windows-cpp-vs2010
Refer below link and it might be useful 1)https://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Developers/Build_Instructions/Prerequisites/Qt#Windows_3 2)http://eecs.vanderbilt.edu/research/hmtl/wp/index.php/qt-vs/
I’m New to QT. I understand that you can force a display refresh, but I’ve pulled all my hair out trying to figure out how. Here is what I’m specifically trying to do.
I press a button (onClick signal event), which runs code that changes an image (QLabel) on the display, waits for input, and then proceeds by changing a new image (different QLabel). I’ve tried everything and the display doesn’t refresh until the onclick signal event code is complete. Right now, I’m not waiting for user input, I’m using usleep(~500 ms) for testing purposes.
From what I read, QT is event driven meaning that I’m basically creating a bunch of events, that get put in a que, and executed when the (onClick signal event) returns to the (main loop)/(event handler). I don’t want to wait until the function is complete, it’s going to make programming extremely painful if I have to accomplish this routine entirely based on events.
How can I force the QLabel pixmap to refresh. I’ve tried everything. Below is all the code I have tried in my onClick signal event handler. (upButton is the name of the QLabel which is a pixmap)
update();
repaint();
ui->upButton->setUpdatesEnabled(TRUE);
update();
repaint();
QPaintEvent paintevent(ui->upButton->childrenRegion());
QPaintEvent * test = &paintevent;
paintEvent(test);
this->changeEvent(test);
ui->upButton->update();
ui->upButton->repaint();
ui->upButton->repaint(ui->upButton->childrenRegion());
repaint();
QApplication::sendPostedEvents();
this->parentWidget()->update();
usleep(100000);
As you can see, I’m just shooting in the dark at this point. I’ve tried to look at sample code and do all my homework, but I’m lost. Appreciate any help, advice, and or sample code.
I was using sleep to emulate a brief amount of time the computer was waiting for something to happen.
As I stated in my question, I didn’t want to use events because it’s a whole lot of unnecessary work to accomplish something extremely simply.
Also, the ‘event’ that needs to take place for the program to continue, is a USB event. Since I’m using an HID class device, there is no way to set an event to happen without a wait loop. USB HID classes don’t permit setting interrupts, the OS claims the device.
I managed to get the above to work. I walked through the debugger and noticed the display would refresh before the sleep function. Running the program independently, I got random results with the display refreshing 1% of the time. I got rid of the sleep function, and added some other code in it’s place to emulate a delay, and it was fine.
Just for everyone’s knowledge, this is possible, it’s not forbidden, and it’s easy to do with the following:
qApp is a global external variable in the QApplication header.
Because this USB event is making my flow tricky, I stumbled upon the QWaitCondition Class. I was going to start a process waiting for the USB event. I would wait until the process releases the wait condition for my routine to continue.
But if anyone thinks this is a bad idea, please, speak out. I really do appreciate your feedback PiedPiper and Hostile Fork.
Thank you.
You shouldn’t be waiting for input in your event handler. You need to rethink the logic of your program to use events the way they were intended. All the update() and repaint() calls in your code are unnecessary if you return to the event loop.
How do I check whether a file exists in a given path or not in Qt?
My current code is below:
QFile Fout("/Users/Hans/Desktop/result.txt");
if(!Fout.exists())
{
eh.handleError(8);
}
else
{
// ......
}
But when I run the code it is not giving the error message specified in handleError
even though the file I mentioned in the path does not exist.
(TL;DR at the bottom)
I would use the QFileInfo
-class (docs) - this is exactly what it is made for:
The QFileInfo class provides system-independent file information.
QFileInfo provides information about a file’s name and position (path) in the file system, its access rights and whether it is a directory or symbolic link, etc. The file’s size and last modified/read times are also available. QFileInfo can also be used to obtain information about a Qt resource.
This is the source code to check whether a file exists:
(don’t forget to add the corresponding #include
-statement)
bool fileExists(QString path) {
QFileInfo check_file(path);
// check if file exists and if yes: Is it really a file and no directory?
if (check_file.exists() && check_file.isFile()) {
return true;
} else {
return false;
}
}
Also consider: Do you only want to check if the path exists (exists()
) or do you want to also make sure that this is a file and not a directory (isFile()
)?
Be careful: The documentation of the exists()
-function says:
Returns true if the file exists; otherwise returns false.
Note: If file is a symlink that points to a non-existing file, false is returned.
This is not precise. It should be:
Returns true if the path (i.e. file or directory) exists; otherwise returns false.
TL;DR
(with shorter version of the function above, saving a few lines of code)
#include <QFileInfo>
bool fileExists(QString path) {
QFileInfo check_file(path);
// check if path exists and if yes: Is it really a file and no directory?
return check_file.exists() && check_file.isFile();
}
TL;DR for Qt >=5.2
(using exists
as a static
which was introduce in Qt 5.2; the docs say the static function is faster, though I’m not sure this is still the case when also using the isFile()
method; at least this is a one-liner then)
You can use the QFileInfo::exists()
method:
#include <QFileInfo>
if(QFileInfo("C:\\exampleFile.txt").exists()){
//The file exists
}
else{
//The file doesn't exist
}
If you want it to return true
only if the file exists and false
if the path exists but is a folder, you can combine it with QDir::exists()
:
#include <QFileInfo>
#include <QDir>
QString path = "C:\\exampleFile.txt";
if(QFileInfo(path).exists() && !QDir(path).exists()){
//The file exists and is not a folder
}
else{
//The file doesn't exist, either the path doesn't exist or is the path of a folder
}
Can someone suggest what’s the best uses for those libraries today? Is it just GUI, or do they have database, XML, networking, threading, etc support too?
I was reading about them, and considered starting to learning/using one of them.
What is the most common one? What’s the difference between them? Why would you choose one over the other?
As you seem to primarily target Linux, then the choice mostly depends on the programming language you want to use.
If you code in C, then obviously go for GTK+
If you code in C++, go for Qt, otherwise you will need Gtkmm (a C++ wrapper over GTK+)
If you code in Python, both GTK+ and Qt have bindings for the language: see PyGtk, PyQt and PySide (the one launched by Nokia themselves).
If you code in Java, Qt is no more a viable option imho as Nokia discontinued Qt Jambi (the Java bindings for Qt).
Also, Qt is more top-notch regarding its scenegraph QGraphicsScene API, its scripting engine built over Javascript Core (the engine powering WebKit), its state machine and animations framework, and the declarative UI.
GTK+ doesn’t offer that much although you can use Clutter alongside with it.
If you’re specifically looking into DB, XML (GTK+ has a parser for a subset of XML) and threading (GTK+ has GLib) features then Qt will offer all that in QtSql, QtXml and QtConcurrent.
All in all, I would say Qt is a sure choice. But GTK+ is very capable as well.
I’m not sure you will get a crystal clear answer for your question, which explains why some people keep preferring Gnome over KDE or vice-versa. Choose what works best for you.
PS: I you plan to also target Symbian, then go for Qt.
EDIT: Something that is also great with Qt is QtWebView
: it brings Chromium into your Qt application to display web content. Others are embedding web content into their application using for instance Awesomium or Berkelium.
I’ve used GTK+, QT and wxWidgets before. Here’s a brief summary:
For my first cross platform UI project I decided to go for wxWidgets mainly because at the time the license wasn’t as restrictive as QT’s (QT was GPL and only for Linux) and it had platform specific UI (unlike GTK). The project worked out well but there were quite a few glitches getting it to compile and run properly in other platforms - sometimes some events were fired up differently and such. Also GDI in wxWidgets was pretty slow.
Next I used GTK for a different project in python. For this I used the python bindings and everything worked out more or less smoothly. I didn’t quite like the fact that the UI didn’t look native on Windows and Mac and also when you launch a GTK+ app it always debug outputs loads of CRITICAL warnings which seem fine to ignore. :S
Finally, I did a very simple QT project now that Nokia has acquired it and was brilliant. The best of the three. First off, if you’re not an old schooler who prefers VI or Emacs, QtCreator is brilliant. I really love VI and used it for years but I much prefer QtCreator for C++ QT projects. Regarding the library I also liked a lot the documentation and the APIs provided. QT has a concept of slots and signals which introduce new C++ keywords and a preprocessor. Basically, after reading a tutorial you’ll get it easily and will start to love it. I’m now doing iPhone dev and it does feel a bit like Cocoa’s/Interface Builder’s UI paradigm.
Summary: I’d go for QT hands down. The license is pretty good and the SDK and documentation really nice.
I have never used GTK, but from my personal experience using Qt:
It is much more than a simple GUI. It’s a whole application framework. I used to think of it as the Java libraries for C++. It provides all you mention – database, XML, networking and threading, and more. It also provides things such as containers and iterators, and counterparts to a number of boost libraries.
The thing that impressed me most when starting to use Qt was the extremely extensive documentation. You get a program called Qt Assistant, which provides fully indexed and searchable API documentation on your desktop, as well as numerous code examples and tutorials. I found it made a big difference in searching the web each time for API info. Very quick access when you need to remember a method signature.
I am not sure which is most common; that’s probably hard to measure accurately. They’re certainly both popular. As Gnome is the default desktop of Ubuntu, and Gnome sits on top of GTK, it obviously has widespread usage. Of course, KDE is very popular as well. Nokia is heavily pushing Qt in the mobile space – their Maemo OS, used on the new N900 for example, is soon to switch to Qt as the default toolkit (currently it is GTK.) I believe Qt will also soon become the default toolkit for Symbian OS.
I have not used Qt Creator, but I have heard many good things about it. It is a C++ IDE with obvious heavy integration with Qt. It also has fake vim emulation which is always nice if you like that kind of thing!
Qt uses qmake for build configuration. I found this much nicer than having to write your own makefiles. I do not know what GTK uses for building.
A couple of things I found a bit offputting with Qt at first was its big uses of preprocessor macros. The signal/slots system provides a nice mechanism for event/message passing in your application, but it does feel a bit like magic that may not be easily portable to another toolkit if you ever want to. Also, the moc (meta-object compiler), while I’m not entirely sure what it does, also feels a bit too much like magic going on behind the scenes.
All in all, though, I would recommend Qt, particularly if you are learning. It has really amazing documentation and a nice IDE, and busy forums. You’ll be able to build C++ apps very rapidly with it, particularly with the QML coming in 4.7.
I’m getting the error
Trying to compile a project on QtCreator. It happens when I try to create an instance of an user defined class, Layer
. That class consists of a header, layer.h
, and a implementation, layer.cpp
. It was tested and works in another programs. On my project, it is included in qtwidget.h
and the error happens when I try to use it on qtwidget.cpp
. For example:
Having this line on qtwidget.cpp
is enough for the error to show up.
This is such a generic error that I’m clueless on how to isolate it any further, but if it helps, I’ve included the whole project on this git repo.
In my opinion, the error message that Qt Creator displays is quite misleading until you understand it, but does not prevent splitting the template class into a header and implementation file. If you think about the message:
the problem, I originally thought when I saw this, is that it states this error on its own in the Issues output and can lead the user into thinking that the problem is due to the architecture. Actually, all its saying is that there’s a defined symbol (often function) whose matching implementation wasn’t found.
If you change from Issues to the Compile Output window and scroll up, you’ll be able to see exactly what symbols can’t be found; mine’s displayed in red. It’s just annoying that the detail of the missing symbol(s) doesn’t show up in the Issues view.
It’s easy to replicate this error by just adding a function definition into a header and without implementing the function, call it from the .cpp file. You’ll then see something like this in the Issues window
Switching to the Compile Output view and scrolling up displays this: -
So now we see that tthe actual problem is that the function DoSomeStuff in the class called PGGui is being called from the constructor PGGui::PGGui, but the body of DoSomeStuff is missing, as its symbol is not found.
Fortunately I’ve managed to solve my problem before any answers, so, if anyone is experiencing anything similar, the issue was that it seems you can’t split a templated class into a .cpp and a .h file. Putting all declarations of the .cpp
file back into the .h
solved the issue.
I still had a leftover problem, though: duplicated symbols (which was the reason I split it). This time, declaring a variable as external
in the .h
, and redeclaring it without the external
keyword in one (and only one) .cpp
file solved the issue for good.
I recently tried to use Qt Creator 1.3.2, Qt 4.6.2, and GCC 4.4.0 (32-bit version) on Windows 7 (64-bit) to compile an application using some of the experimental C++0x extensions and encountered the following (fatal) error:
This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.
In my search for a solution, I came across the thread qmake and compiler flags?, and added the following to the .pro file:
but that didn’t seem to make a difference.
So, I expect there’s some tag I need to add to the .pro (project) file, but I’ve never messed with the GCC compiler switches in Qt, QMake, and QtCreator before, and I am uncertain about the proper invokation / incantation. So, my question is how do you set GCC compiler switches when using QtCreator, QMake, and Qt?
It boils down to reading the manual. Instead of using CXXFLAGS
in the .pro file, you need to use QMAKE_CXXFLAGS
as in:
main.cpp:
main.pro:
You should use
to enable C++11 compiler flags automatically.
Look for .prf
files in your qt installation. I don’t know where they might be on windows, but on my Linux installation they are under /opt/Qt/5.4/gcc_64/mkspecs/features
.
You might want to read the qmake documentation for that:
qmake can be set up with extra configuration features that are specified in feature (.prf) files. These extra features often provide support for custom tools that are used during the build process. To add a feature to the build process, append the feature name (the stem of the feature filename) to the CONFIG variable.
You can add your own features.
Here is what I found on my system. CONFIG += name will enable the feature:
./android/android_deployment_settings.prf
./android/android.prf
./build_pass.prf
./c++11.prf
./c++14.prf
./cmake_functions.prf
./configure.prf
./create_cmake.prf
./ctest_testcase_common.prf
./ctest_testcase_installed.prf
./ctest_testcase.prf
./dbusadaptors.prf
./dbusinterfaces.prf
./declarative_debug.prf
./default_post.prf
./default_pre.prf
./designer_defines.prf
./device_config.prf
./egl.prf
./exceptions_off.prf
./exceptions.prf
./exclusive_builds_post.prf
./exclusive_builds.prf
./gcov.prf
./include_source_dir.prf
./incredibuild_xge.prf
./java.prf
./lex.prf
./link_ltcg.prf
./link_pkgconfig.prf
./ltcg.prf
./mac/default_post.prf
./mac/default_pre.prf
./mac/objective_c.prf
./mac/rez.prf
./mac/sdk.prf
./moc.prf
./no_debug_info.prf
./precompile_header.prf
./qfeatures.prf
./qlalr.prf
./qml1_module.prf
./qml1_plugin.prf
./qml_debug.prf
./qml_module.prf
./qml_plugin.prf
./qmltestcase.prf
./qpa/basicunixfontdatabase.prf
./qpa/genericunixfontdatabase.prf
./qt_android_deps.prf
./qt_app.prf
./qt_build_config.prf
./qt_build_paths.prf
./qt_common.prf
./qt_config.prf
./qt_docs.prf
./qt_docs_targets.prf
./qt_example_installs.prf
./qt_functions.prf
./qt_headersclean.prf
./qt_helper_lib.prf
./qt_installs.prf
./qt_module_headers.prf
./qt_module.prf
./qt_module_pris.prf
./qt_parts.prf
./qt_plugin.prf
./qt.prf
./qt_targets.prf
./qt_tool.prf
./resolve_config.prf
./resolve_target.prf
./resources.prf
./silent.prf
./simd.prf
./spec_post.prf
./spec_pre.prf
./testcase.prf
./testcase_targets.prf
./testcocoon.prf
./testlib_defines.prf
./uic.prf
./unix/bsymbolic_functions.prf
./unix/dylib.prf
./unix/hide_symbols.prf
./unix/largefile.prf
./unix/opengl.prf
./unix/openvg.prf
./unix/separate_debug_info.prf
./unix/thread.prf
./unix/x11inc.prf
./unix/x11lib.prf
./unix/x11.prf
./unix/x11sm.prf
./use_c_linker.prf
./vxworks.prf
./warn_off.prf
./warn_on.prf
./wayland-scanner.prf
./win32/console.prf
./win32/default_pre.prf
./win32/dumpcpp.prf
./win32/idcidl.prf
./win32/msvc_mp.prf
./win32/opengl.prf
./win32/openvg.prf
./win32/qt_config.prf
./win32/qt_dll.prf
./win32/rtti_off.prf
./win32/rtti.prf
./win32/stl_off.prf
./win32/stl.prf
./win32/windeployqt.prf
./win32/windows.prf
./winrt/console.prf
./winrt/font_deployment.prf
./winrt/package_manifest.prf
./yacc.prf
The only way that really works for me is to add it to QMAKE_CXXFLAGS
.
The CONFIG += c++11
does not add -std=c++11
to the compile command.
I have subclassed QDialog
to implement functionality similar to QMessageBox
( I needed this to allow for customization). It has a text message and OK, Cancel buttons. I am showing the dialog using exec()
to make it blocking. Now, how do I return values of true/false when the user clicks on OK/Cancel?
I tried connecting the buttons to setResult()
and then, return the result value when clicked, but
class MyMessageBox : public QDialog {
Q_OBJECT
private slots:
void onOKButtonClicked() { this->setResult(QDialog::Accepted); }
void onCancelButtonClicked() { this->setResult(QDialog::Rejected); }
public:
MyMessageBox(QMessageBox::Icon icon, const QString& title,
const QString& text, bool showCancelButton = true,
QWidget* parent = 0);
virtual void resizeEvent(QResizeEvent* e);
QDialog::DialogCode showYourself()
{
this->setWindowModality(Qt::ApplicationModal);
this->exec();
return static_cast<QDialog::DialogCode>(this->result());
}
};
The user will instantiate the class and call showYourself()
which is expected to return the value and also close(and delete) the dialog.
I have posted partial code. Let me know if you need more and I will post the complete version.
Some points :
setResult()
yourself, use QDialog::accept() and QDialog::reject().
onOKButtonClicked
and onCancelButtonClicked
are unnecessary.
showYourself()
. Just call exec
and with the events information will flow.
You need to add this code before showing the dialog (this
assume it is in a dialog method):
QObject::connect(acceptButton, SIGNAL(clicked()), this, SLOT(accept()));
QObject::connect(rejectButton, SIGNAL(clicked()), this, SLOT(reject()));
In the caller object you have
Another solution:
// set signal and slot for "Buttons"
connect(YesButton, SIGNAL(clicked()), dlg, SLOT(accept()));
connect(NoButton, SIGNAL(clicked()), dlg, SLOT(reject()));
// show modal window event loop and wait for button clicks
int dialogCode = dlg->exec();
// act on dialog return code
if(dialogCode == QDialog::Accepted) { // YesButton clicked }
if(dialogCode == QDialog::Rejected) { // NoButton clicked }
Case 1 Clicking the buttons does not close the dialog box.
For this you have to close the dialog on respective SLOTS
, so Use
void onOKButtonClicked(){ this->setResult(QDialog::Accepted); this->close();}
void onCancelButtonClicked(){ this->setResult(QDialog::Rejected);this->close();}
Note: Only after you have clicked the Ok button or Cancel button in a standard QMessageBox, setResult() function is triggered and the status is changed. It’s not the same effect when done vice versa.
Case 2 The return value is incorrect.
I think only after your dialog gets closed, you will have the result available in result()
function. So I guess it will be solved, after you have made the changes specified in Case 1.
If it still persists, use your own private member function to resolve it.
I inherited a class from QObject :
class Parent: public QObject
{
Q_OBJECT
QObject* cl;
public:
Parent(QObject *parent=0):QObject(parent) {
cl = NULL;
}
QObject* getCl() const {
return cl;
}
void setCl(QObject *obj) {
cl = obj;
}
};
But when I write :
I get the following error:
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall Parent::metaObject(void)const " (?metaObject@Parent@@UBEPBUQMetaObject@@XZ)
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void * __thiscall Parent::qt_metacast(char const *)" (?qt_metacast@Parent@@UAEPAXPBD@Z)
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual int __thiscall Parent::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@Parent@@UAEHW4Call@QMetaObject@@HPAPAX@Z)
You should delete the debug
folder of your application and run it again to correct this problem.
If you’re using Visual Studio, delete the line Q_OBJECT
from the header file, save the file, put Q_OBJECT
back into the header file, save the file again. This should generate the moc_*
file and should build and link correctly.
I noticed some answers are based on Visual Studio.
This answer is based on Qt Creator.
Unlike the name suggest, Rebuild Project
will not wipe out everything and build from scratch. If you recently added QObject
(and/or Q_OBJECT) to your class, you’ll have to run qmake
again, e.g.
This is because, by default, qmake
only runs when you do significant changes to your solution like adding new source files or modify the .pro
file. If you make edits to an existing file, it doesn’t know it needs to run qmake
.
As a fall back, to brute force Qt to build everything from scratch, delete the Debug
or Release
folder.
I have a Qt dialog application. Now I dont want that dialog to be resizeable. I am not sure how to achieve this. I tried a bunch of things but still when the dialog launches this dialog can be resized.
What is the property that i should set to disable the dialog/Widget resize.
I also tried
But i get an error saying..
source\nimcac_settingsMain.cpp(36) : error C2248: **'QSizePolicy::QSizePolicy' : cannot access private member declared in class 'QSizePolicy'** p:\ThirdPartyExports\Qt\export\4.3\4.3.1f14\include\QtGui\../../src\gui\ kernel\qsizepolicy.h(177) : see declaration of 'QSizePolicy::QSizePolicy' p:\ThirdPartyExports\Qt\export\4.3\4.3.1f14\include\QtGui\../../src\gui\ kernel\qsizepolicy.h(34) : see declaration of 'QSizePolicy'
Kindly help me out with this.
I don’t know if you already tried it, but QWidget::setFixedSize
should do what you want
The compile error you get is because you try to pass a QSizePolicy::Policy
to setSizePolicy(QSizePolicy)
, but there’s no implicit conversion from QSizePolicy::Policy
(which is the policy for one dimension) to QSizePolicy
(which is a class containing, among other things, one Policy
per dimension (height, width)). QSizePolicy
doesn’t work on top-level widgets (windows) anyway, though.
setFixedSize()
only works if you know the size of the dialog in advance (and usually you don’t, what with changing font sizes and languages). You can do
but it’s much better to use
That lets the layout determine the size of the dialog, but doesn’t allow resizing, which I assume is what you were asking for.
I have to compare two Qstrings in qt,
say,
I have tried using ,
&
still both methods goes inside if condition & returns true.
It worked after Rebuilding the Project , I think this is the problem with QT CREATOR
You can use :
The code below works fine for me.
int main(int argv, char **args)
{
QString str1="1005",str2="1006";
if(str1 == str2)
qDebug()<<"This should not print";
qDebug()<<"Everything Ok";
}
Output:
I don’t know, why your code is not working, when is should have been fine. Recheck other parts of your code.
I’m a long time Java user learning C++ with Qt and I’m having a lot of trouble understanding how methods work. Right now, I’m trying to figure out databases, and tried to simplify my code with a header. Normally in Java I would just have a class called DatabaseControl with a void method that would execute whatever I wanted. For example, adding an employee to a database, as I’m doing now. I’d instantiate the class, by doing something like
and then execute the method with
which would bring up the series of input boxes for the user to input the information on the employee - name, department, etc.
So, now over to C++. I have my header
class DatabaseControl
{
public:
DatabaseControl();
~DatabaseControl();
//Methods
void addEmployee();
};
I don’t have any parameters in my constructors because all I want to do is call the “addEmployee” method in my main as I’ve shown above. In the same header file I have this below my class declaration
void DatabaseControl::addEmployee(){
QSqlQuery qry;
bool ok;
QString firstName = QInputDialog::getText(NULL, "QInputDialog::getText()",
"Employee first name:", QLineEdit::Normal,
NULL, &ok);
if (ok && !firstName.isEmpty()){}
else{
QMessageBox msgBox;
msgBox.setWindowTitle("Error");
msgBox.setText("Failed to add employee.\nReason: No employee name given.");
msgBox.exec();
}
QString lastName = QInputDialog::getText(NULL, "QInputDialog::getText()",
"Employee last name:", QLineEdit::Normal,
NULL, &ok);
if (ok && !lastName.isEmpty()){
qry.prepare("INSERT INTO employees (firstname, lastname)" "VALUES (:f1, :f2)");
qry.bindValue(":f1", firstName);
qry.bindValue(":f2", lastName);
qry.exec();
}
else{
QMessageBox msgBox;
msgBox.setWindowTitle("Error");
msgBox.setText("Failed to add employee.\nReason: No employee name given.");
msgBox.exec();
}
}
and then in my main I have this:
void MainWindow::on_addEmployee_clicked()
{
DatabaseControl myDBControl();
myDBControl.addEmployee();
}
which I expected to just run the addEmployee method I wrote in the header file. However, when I compile, I get the error Error: C2228: left of ‘.addEmployee’ must have class/struct/union
I’ve looked at other instances of this error and don’t really understand exactly what’s wrong, and I feel it comes from my misunderstanding of methods in C++, because I know in Java something like this would work without issue (assuming the code in the header is correct which it very well may not be)
You made an error here:
You declared a function called myDBControl
taking no arguments and returning a DatabaseControl
.
Object declarations without any constructor arguments must omit the ()
:
This is related to (but is not precisely) the “most vexing parse”, in that it’s caused by the same language rule that statements are function declarations if they can be so parsed.
You need to say this:
You need to say this:
Possible Duplicate:
QString to char conversion
I have a function (fopen in STL) that gives a char* argument as a path in my computer, but I must use QString in that place so it doesn’t work.
How can I convert QString to char* to solve this problem?
See here at How can I convert a QString to char* and vice versa?
In order to convert a QString to a char*, then you first need to get a latin1 representation of the string by calling toLatin1() on it which will return a QByteArray. Then call data() on the QByteArray to get a pointer to the data stored in the byte array. See the documentation:
https://doc.qt.io/qt-5/qstring.html#toLatin1 https://doc.qt.io/qt-5/qbytearray.html#data
See the following example for a demonstration:
int main(int argc, char **argv) { QApplication app(argc, argv); QString str1 = "Test"; QByteArray ba = str1.toLatin1(); const char *c_str2 = ba.data(); printf("str2: %s", c_str2); return app.exec(); }
Note that it is necessary to store the bytearray before you call data() on it, a call like the following
will make the application crash as the QByteArray has not been stored and hence no longer exists
To convert a char* to a QString you can use the QString constructor that takes a QLatin1String, e.g:
See the documentation:
https://doc.qt.io/qt-5/qlatin1string.html
Of course, I discovered there is another way from this previous SO answer:
You could use QFile rather than std::fstream.
Alternatively convert the QString into a char* as follows:
The QString is in UTF-16 so it is converted toLatin1() here but QString has a couple of different conversions including toUtf8() (check your file-system it may use UTF-8).
As noted by @0A0D above: don’t store the char* in a variable without also getting a local copy of the QByteArray.
char const* fileName = qString.toLatin1().data();
std::ifstream file(fileName); // fileName not valid here.
This is because toLatin1() returns an object of QByteArray. As it is not actually bound to a variable it is a temporary that is destroyed at the end of the expression. Thus the call to data() here returns a pointer to an internal structure that no longer exists after the ‘;’.
I want to cross compile the Qt libraries (and eventually my application) for a Windows x86_64 target using a Linux x86_64 host machine. I feel like I am close, but I may have a fundamental misunderstanding of some parts of this process.
I began by installing all the mingw packages on my Fedora machine and then modifying the win32-g++
qmake.conf file to fit my environment. However, I seem to be getting stuck with some seemingly obvious configure options for Qt: -platform
and -xplatform
. Qt documentation says that -platform
should be the host machine architecture (where you are compiling) and -xplatform
should be the target platform for which you wish to deploy. In my case, I set -platform linux-g++-64
and -xplatform linux-win32-g++
where linux-win32-g++ is my modified win32-g++ configuration.
My problem is that, after executing configure with these options, I see that it invokes my system’s compiler instead of the cross compiler (x86_64-w64-mingw32-gcc). If I omit the -xplatform
option and set -platform
to my target spec (linux-win32-g++), it invokes the cross compiler but then errors when it finds some Unix related functions aren’t defined.
Here is some output from my latest attempt: http://pastebin.com/QCpKSNev.
Questions:
When cross-compiling something like Qt for Windows from a Linux host, should the native compiler ever be invoked? That is, during a cross compilation process, shouldn’t we use only the cross compiler? I don’t see why Qt’s configure script tries to invoke my system’s native compiler when I specify the -xplatform
option.
If I’m using a mingw cross-compiler, when will I have to deal with a specs file? Spec files for GCC are still sort of a mystery to me, so I am wondering if some background here will help me.
In general, beyond specifying a cross compiler in my qmake.conf, what else might I need to consider?
Just use M cross environment (MXE). It takes the pain out of the whole process:
Get it:
$ git clone https://github.com/mxe/mxe.git
```</li>
<li><p>Install <a href="http://mxe.cc/#requirements" rel="noreferrer">build dependencies</a></p></li>
<li><p>Build Qt for Windows, its dependencies, and the cross-build tools;
this will take about an hour on a fast machine with decent internet access;
the download is about 500MB:</p>
```c
$ cd mxe && make qt
```</li>
<li><p>Go to the directory of your app and add the cross-build tools to the <strong>PATH</strong> environment variable:</p>
```c
$ export PATH=<mxe root>/usr/bin:$PATH
```</li>
<li><p>Run the Qt Makefile generator tool then build:</p>
```c
$ <mxe root>/usr/i686-pc-mingw32/qt/bin/qmake && make
```</li>
<li><p>You should find the binary in the ./release directory:</p>
```c
$ wine release/foo.exe
```</li>
</ul>
<strong>Some notes</strong>:
<ul>
<li><p>Use the master branch of the MXE repository; it appears to get a lot more love from the development team.</p></li>
<li><p>The output is a 32-bit static binary, which will work well on 64-bit Windows.</p></li>
</ul>
#### Answer 2 (score 16)
(This is an update of @Tshepang's answer, as MXE has evolved since his answer)
<h5>Building Qt</h1>
Rather than using `make qt` to build Qt, you can use `MXE_TARGETS` to control your target machine and toolchain (32- or 64-bit). MXE started using `.static` and `.shared` as a part of the target name to show which type of lib you want to build.
```c
# The following is the same as `make qt`, see explanation on default settings after the code block.
make qt MXE_TARGETS=i686-w64-mingw32.static # MinGW-w64, 32-bit, static libs
# Other targets you can use:
make qt MXE_TARGETS=x86_64-w64-mingw32.static # MinGW-w64, 64-bit, static libs
make qt MXE_TARGETS=i686-w64-mingw32.shared # MinGW-w64, 32-bit, shared libs
# You can even specify two targets, and they are built in one run:
# (And that's why it is MXE_TARGET**S**, not MXE_TARGET ;)
# MinGW-w64, both 32- and 64-bit, static libs
make qt MXE_TARGETS='i686-w64-mingw32.static x86_64-w64-mingw32.static'
In @Tshepang’s original answer, he did not specify an MXE_TARGETS
, and the default is used. At the time he wrote his answer, the default was i686-pc-mingw32
, now it’s i686-w64-mingw32.static
. If you explicitly set MXE_TARGETS
to i686-w64-mingw32
, omitting .static
, a warning is printed because this syntax is now deprecated. If you try to set the target to i686-pc-mingw32
, it will show an error as MXE has removed support for MinGW.org (i.e. i686-pc-mingw32).
qmake
As we changed the MXE_TARGETS
, the <mxe root>/usr/i686-pc-mingw32/qt/bin/qmake
command will no longer work. Now, what you need to do is:
If you didn’t specify MXE_TARGETS
, do this:
Update: The new default is now i686-w64-mingw32.static
Ok I think I’ve got it figured out.
Based in part on https://github.com/mxe/mxe/blob/master/src/qt.mk and https://www.videolan.org/developers/vlc/contrib/src/qt4/rules.mak
It appears that “initially” when you run configure (with -xtarget, etc.), it configures then runs your “hosts” gcc to build the local binary file ./bin/qmake
./configure -xplatform win32-g++ -device-option CROSS_COMPILE=$cross_prefix_here -nomake examples ...
then you run normal “make” and it builds it for mingw
so
yes
only if you need to use something other than msvcrt.dll (its default). Though I have never used anything else so I don’t know for certain.
https://stackoverflow.com/a/18792925/32453 lists some configure params.
I just started using Qt and noticed that all the example class definitions have the macro Q_OBJECT
as the first line. What is the purpose of this preprocessor macro?
From the Qt documentation:
The Meta-Object Compiler, moc, is the program that handles Qt’s C++ extensions.
The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.
It simply tells the pre-compiler that this class has gui elements and needs to be run through the ‘moc’ you only need to add this to classes that use the signal/slot mechanism.
But it will be quietly ignored in any other classes - it just adds to the build time.
The MOC (meta object compiler) converts the Q_OBJECT macro included header files in to C++ equivalent source code. It basically controls the signal-slot mechanism, and makes it understandable to the C++ compiler
I’m using Qt5. I am trying to obtain values from a json object. Here is what the json object looks like that I am trying to get data from:
{
"success": true,
"properties": [
{
"ID": 1001,
"PropertyName": "McDonalds",
"key": "00112233445566778899aabbccddeeff"
},
{
"ID": 1002,
"PropertyName": "Burger King",
"key": "10112233445566778899aabbccddeeff"
},
{
"ID": 1003,
"PropertyName": "Taco Bell",
"key": "20112233445566778899aabbccddeeff"
}
]
}
How can I create three arrays that contain properties[x].ID
, properties[x].PropertyName
, and properties[x].key
in Qt?
Edit:
Using QScriptEngine
I tried this:
QString data = (QString)reply->readAll();
QScriptEngine engine;
QScriptValue result = engine.evaluate(data);
qDebug() << result.toString();
Debug is saying “SyntaxError: Parse error”
I figured it out:
QStringList propertyNames;
QStringList propertyKeys;
QString strReply = (QString)reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["properties"].toArray();
foreach (const QJsonValue & value, jsonArray) {
QJsonObject obj = value.toObject();
propertyNames.append(obj["PropertyName"].toString());
propertyKeys.append(obj["key"].toString());
}
Here is an example from How To Manipulate JSON With C++ and Qt.
// reads a json file from disk to QVariantMap
// originally from http://erickveil.github.io/2016/04/06/How-To-Manipulate-JSON-With-C++-and-Qt.html
bool readJsonFile(std::string file_path, QVariantMap& result)
{
// step 1
QFile file_obj(QString::fromStdString(file_path));
if (!file_obj.open(QIODevice::ReadOnly)) {
std::cout << "Failed to open " << file_path << std::endl;
exit(1);
}
// step 2
QTextStream file_text(&file_obj);
QString json_string;
json_string = file_text.readAll();
file_obj.close();
QByteArray json_bytes = json_string.toLocal8Bit();
// step 3
auto json_doc = QJsonDocument::fromJson(json_bytes);
if (json_doc.isNull()) {
std::cout << "Failed to create JSON doc." << std::endl;
return false;
}
if (!json_doc.isObject()) {
std::cout << "JSON is not an object." << std::endl;
return false;
}
QJsonObject json_obj = json_doc.object();
if (json_obj.isEmpty()) {
std::cout << "JSON object is empty." << std::endl;
return false;
}
// step 4
result = json_obj.toVariantMap();
return true;
}
// writes a QVariantMap to disk
bool writeJsonFile(QVariantMap point_map, std::string file_path)
{
QJsonObject json_obj = QJsonObject::fromVariantMap(point_map);
QJsonDocument json_doc(json_obj);
QString json_string = json_doc.toJson();
QFile save_file(QString::fromStdString(file_path));
if (!save_file.open(QIODevice::WriteOnly)) {
std::cout << "failed to open save file" << std::endl;
return false;
}
save_file.write(json_string.toLocal8Bit());
save_file.close();
return true;
}
The Qt documentation for QThread says to create a class from QThread, and to implement the run method.
Below is taken from the 4.7 Qthread documentation…
To create your own threads, subclass QThread and reimplement run(). For example:
class MyThread : public QThread
{
public:
void run();
};
void MyThread::run()
{
QTcpSocket socket;
// connect QTcpSocket's signals somewhere meaningful
...
socket.connectToHost(hostName, portNumber);
exec();
}
So in every single thread I’ve created, I’ve done just that and for most things it works just fine (I do not implement moveToThread(this) in any of my objects and it works great).
I hit a snag last week (managed to get through it by working around where I created my objects) and found the following blog post. Here is basically says that subclassing QThread really isn’t the correct way to do it (and that the documentation is incorrect).
This is coming from a Qt developer so at first glance I was interested and upon further reflection, agree with him. Following OO principles, you really only want to subclass a class to further enhance that class… not to just use the classes methods directly… thats why you instantiate…
Lets say I wanted to move a custom QObject class to a thread… what would be the ‘correct’ way of doing it? In that blog post, he ‘says’ he has an example somewhere… but if someone could further explain it to me it’d be greatly appreciated!
Update:
Since this question gets so much attention, here is a copy and paste of the 4.8 documentation with the ‘proper’ way to implement a QThread.
class Worker : public QObject
{
Q_OBJECT
QThread workerThread;
public slots:
void doWork(const QString ¶meter) {
// ...
emit resultReady(result);
}
signals:
void resultReady(const QString &result);
};
class Controller : public QObject
{
Q_OBJECT
QThread workerThread;
public:
Controller() {
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
connect(workerThread, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(this, SIGNAL(operate(QString)), worker, SLOT(doWork(QString)));
connect(worker, SIGNAL(resultReady(QString)), this, SLOT(handleResults(QString)));
workerThread.start();
}
~Controller() {
workerThread.quit();
workerThread.wait();
}
public slots:
void handleResults(const QString &);
signals:
void operate(const QString &);
};
I still believe that it is worthwhile to point out that they include an extra Worker::workerThread
member that is unnecessary and is never used in their example. Remove that piece and it is a proper example of how to do threading in Qt.
About the only thing I can think of to add is to further state that QObject
s have an affinity with a single thread. This is usually the thread that creates the QObject
. So if you create a QObject
in the app’s main thread and want to use it in another thread, you need to use moveToThread()
to change the affinity.
This saves having to subclass QThread
and creating your objects in the run()
method, thus keeping your stuff nicely encapsulated.
That blog post does include a link to an example. It is pretty short but it shows the basic idea. Create your QObject
s, connect your signals, create your QThread
, move your QObjects
to the QThread
and start the thread. The signal/slot mechanisms will ensure that thread boundaries are crossed properly and safely.
You may have to introduce synchronization if you have to call methods on your object outside of that mechanism.
I know Qt has some other nice threading facilities beyond threads that are probably worth getting familiar with but I have yet to do so :)
Here’s one example of how to use QThread correctly, but it has some issues with it, which are reflected in the comments. In particular, since the order in which the slots are executed isn’t strictly defined, it could lead to various problems. The comment posted on August 6, 2013 gives a nice idea how to deal with this issue. I use something like that in my program, and here’s some example code to clarify.
The basic idea is the same: I create a QThread instance that lives in my main thread, a worker class instance that lives in the new thread I created, and then I connect all the signals.
void ChildProcesses::start()
{
QThread *childrenWatcherThread = new QThread();
ChildrenWatcher *childrenWatcher = new ChildrenWatcher();
childrenWatcher->moveToThread(childrenWatcherThread);
// These three signals carry the "outcome" of the worker job.
connect(childrenWatcher, SIGNAL(exited(int, int)),
SLOT(onChildExited(int, int)));
connect(childrenWatcher, SIGNAL(signalled(int, int)),
SLOT(onChildSignalled(int, int)));
connect(childrenWatcher, SIGNAL(stateChanged(int)),
SLOT(onChildStateChanged(int)));
// Make the watcher watch when the thread starts:
connect(childrenWatcherThread, SIGNAL(started()),
childrenWatcher, SLOT(watch()));
// Make the watcher set its 'stop' flag when we're done.
// This is performed while the watch() method is still running,
// so we need to execute it concurrently from this thread,
// hence the Qt::DirectConnection. The stop() method is thread-safe
// (uses a mutex to set the flag).
connect(this, SIGNAL(stopped()),
childrenWatcher, SLOT(stop()), Qt::DirectConnection);
// Make the thread quit when the watcher self-destructs:
connect(childrenWatcher, SIGNAL(destroyed()),
childrenWatcherThread, SLOT(quit()));
// Make the thread self-destruct when it finishes,
// or rather, make the main thread delete it:
connect(childrenWatcherThread, SIGNAL(finished()),
childrenWatcherThread, SLOT(deleteLater()));
childrenWatcherThread->start();
}
Some background:
The ChildProcesses class is a child process manager that starts new child processes with spawn() calls, keeps the list of the processes currently running and so on. However, it needs to keep track of the children states, which means using waitpid() call on Linux or WaitForMultipleObjects on Windows. I used to call these in non-blocking mode using a timer, but now I want more prompt reaction, which means blocking mode. That’s where the thread comes in.
The ChildrenWatcher class is defined as follows:
class ChildrenWatcher: public QObject {
Q_OBJECT
private:
QMutex mutex;
bool stopped;
bool isStopped();
public:
ChildrenWatcher();
public slots:
/// This is the method which runs in the thread.
void watch();
/// Sets the stop flag.
void stop();
signals:
/// A child process exited normally.
void exited(int ospid, int code);
/// A child process crashed (Unix only).
void signalled(int ospid, int signal);
/// Something happened to a child (Unix only).
void stateChanged(int ospid);
};
Here how it works. When all this stuff is started, the ChildProcess::start() method is called (see above). It creates a new QThread and a new ChildrenWatcher, which is then moved to the new thread. Then I connect three signals which inform my manager about the fate of its child processes (exited/signalled/god-knows-what-happened). Then starts the main fun.
I connect QThread::started() to the ChildrenWatcher::watch() method so it is started as soon as the thread is ready. Since the watcher lives in the new thread, that’s where the watch() method is executed (queued connection is used to call the slot).
Then I connect the ChildProcesses::stopped() signal to the ChildrenWatcher::stop() slot using Qt::DirectConnection because I need to do it asynchronously. This is needed so my thread stops when the ChildProcesses manager is no longer needed. The stop() method looks like this:
And then ChildrenWatcher::watch():
void ChildrenWatcher::watch()
{
while (!isStopped()) {
// Blocking waitpid() call here.
// Maybe emit one of the three informational signals here too.
}
// Self-destruct now!
deleteLater();
}
Oh, and the isStopped() method is just a convenient way to use a mutex in the while() condition:
bool ChildrenWatcher::isStopped()
{
bool stopped;
mutex.lock();
stopped = this->stopped;
mutex.unlock();
return stopped;
}
So what happens here is that I set the stopped flag when I need to finish, and then the next time isStopped() is called it returns false and the thread ends.
So what happens when the watch() loop ends? It calls deleteLater() so the object self-destructs as soon as control is returned to the thread event loop which happens just right after the deleteLater() call (when watch() returns). Going back to ChildProcesses::start(), you can see that there is a connection from the destroyed() signal of the watcher to the quit() slot of the thread. This means that the thread automatically finishes when the watcher is done. And when it’s finished, it self-destructs too because its own finished() signal is connected to its deleteLater() slot.
This is pretty much the same idea as Maya posted, but because I use the self-destruct idiom, I don’t need to depend on the sequence in which the slots are called. It’s always self-destruct first, stop thread later, then it self-destructs too. I could define a finished() signal in the worker, and then connect it to its own deleteLater(), but that would only mean one connection more. Since I don’t need a finished() signal for any other purpose, I chose to just call deleteLater() from the worker itself.
Maya also mentions that you shouldn’t allocate new QObjects in the worker’s constructor because they won’t live in the thread you move the worker to. I’d say do it anyway because that’s the way OOP works. Just make sure all those QObjects are children of the worker (that is, use the QObject(QObject*) constructor) - moveToThread() moves all the children along with the object being moved. If you really need to have QObjects that aren’t children of your object, then override moveToThread() in your worker so it moves all the necessary stuff too.
Not to detract from @sergey-tachenov’s excellent answer, but in Qt5 you can stop using SIGNAL and SLOT, simplify your code and have the advantage of compile time checking:
void ChildProcesses::start()
{
QThread *childrenWatcherThread = new QThread();
ChildrenWatcher *childrenWatcher = new ChildrenWatcher();
childrenWatcher->moveToThread(childrenWatcherThread);
// These three signals carry the "outcome" of the worker job.
connect(childrenWatcher, ChildrenWatcher::exited,
ChildProcesses::onChildExited);
connect(childrenWatcher, ChildrenWatcher::signalled,
ChildProcesses::onChildSignalled);
connect(childrenWatcher, ChildrenWatcher::stateChanged,
ChildProcesses::onChildStateChanged);
// Make the watcher watch when the thread starts:
connect(childrenWatcherThread, QThread::started,
childrenWatcher, ChildrenWatcher::watch);
// Make the watcher set its 'stop' flag when we're done.
// This is performed while the watch() method is still running,
// so we need to execute it concurrently from this thread,
// hence the Qt::DirectConnection. The stop() method is thread-safe
// (uses a mutex to set the flag).
connect(this, ChildProcesses::stopped,
childrenWatcher, ChildrenWatcher::stop, Qt::DirectConnection);
// Make the thread quit when the watcher self-destructs:
connect(childrenWatcher, ChildrenWatcher::destroyed,
childrenWatcherThread, QThread::quit);
// Make the thread self-destruct when it finishes,
// or rather, make the main thread delete it:
connect(childrenWatcherThread, QThread::finished,
childrenWatcherThread, QThread::deleteLater);
childrenWatcherThread->start();
}
Does C++ have any equivalent to python’s function os.path.join
? Basically, I’m looking for something that combines two (or more) parts of a file path so that you don’t have to worry about making sure the two parts fit together perfectly. If it’s in Qt, that would be cool too.
Basically I spent an hour debugging some code and at least part of it was because root + filename
had to be root/ + filename
, and I’m looking to avoid that in the future.
Check out QDir for that:
Only as part of Boost.Filesystem library. Here is an example:
#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main ()
{
fs::path dir ("/tmp");
fs::path file ("foo.txt");
fs::path full_path = dir / file;
std::cout << full_path << std::endl;
return 0;
}
Here is an example of compiling and running (platform specific):
Similar to @user405725’s answer (but not using boost), and mentioned by @ildjarn in a comment, this functionality is available as part of std::experimental::filesystem. The following code compiles using Microsoft Visual Studio 2015 Community Edition:
#include <iostream>
#include <filesystem>
namespace fs = std::experimental::filesystem;
int main()
{
fs::path dir ("/tmp");
fs::path file ("foo.txt");
fs::path full_path = dir / file;
std::cout << full_path << std::endl;
return 0;
}
I want to send a Signal from C++ to a Slot in my QML File. I already got it working without and primitive type parameters, although if I want to send a QString
to my QML Slot I get an error whilst connecting.
I connect in main.cpp
QObject *contentView = rootObject->findChild<QObject*>(QString("contentView"));
QObject::connect(&myObj, SIGNAL(finishedGatheringDataForItem(QString)),
contentView, SLOT(updateViewWithItem(QString)));
the relavant part of my qml File
Rectangle {
objectName: "contentView"
function updateViewWithItem(string) { console.log('got some Items'); } // slot
}
Error:
I think it would be best if you check this tutorial:
http://doc.qt.io/qt-4.8/qtbinding.html
especially this section:
http://doc.qt.io/qt-4.8/qtbinding.html#receiving-signals
I think your mistake in this case might either be that you didn’t declare it as a slot or you didn’t make it invocable. Both options are explained in the Qt Tutorial.
Also, you need to use a QVariant in order to exchange data between C++ and QML. You can also register types, e.g. Widgets and stuff, so that you can use them in QML as a “native” type like a rectangle. In most cases this is not recommended, except if you need some certain extern class or some data that you cannot display otherwise in your QML Interface.
The reason for the QVariant is the Script based approach of QML. The QVariant basically contains your data and a desription of the data type, so that the QML knows how to handle it properly. That’s why you have to specify the parameter in QML with String, int etc.. But the original data exchange with C++ remains a QVariant
I have used the qmlRegisterType before, but it is a very inconvenient Solution for simple data types. It is rather used for more complex data, such as custom Widgets, Canvas or Video elements that QML does not natively support or extended QStandardItemModels
. It is a more convenient way to exchange data between QML and C++ and does not need Signals or Slots in first instance, because the QStandardItemModel updates the GUI automatically. For using the QStandardItemModel you need to register the Type with qmlRegisterType.. . The Model can then be used in Model based Views such as the ListView etc.
I attached a tutorial for this topic, it describes how to use the QListModel.
You should use Connections in this case (maybe it’s the only way to connect).
Put your object myObj to QML file by setContextProperty
qmlVectorForm->rootContext()->setContextProperty("YourObject", myOb);
```</li>
<li><p>Your signal is</p>
```c
finishedGatheringDataForItem(QString signalString)
```</li>
<li><p>In QML file, add Connectios likes below:</p>
```c
Connections {
target: YourObject
onFinishedGatheringDataForItem: {
qmlString = signalString
}
}
```</li>
</ol>
</b> </em> </i> </small> </strong> </sub> </sup>
### 87: switch/case statement in C++ with a QString type (score [68450](https://stackoverflow.com/q/5452188.html) in 2019)
#### Question
I want to use switch-case in my program but the compiler gives me this error:
```c
switch expression of type 'QString' is illegal
How can I use the switch
statement with a QString
?
My code is as follows:
bool isStopWord( QString word )
{
bool flag = false ;
switch( word )
{
case "the":
flag = true ;
break ;
case "at" :
flag = true ;
break ;
case "in" :
flag = true ;
break ;
case "your":
flag = true ;
break ;
case "near":
flag = true ;
break ;
case "all":
flag = true ;
break ;
case "this":
flag = true ;
break ;
}
return flag ;
}
How can I use the switch statement with a QString?
You can’t. In C++ language switch
statement can only be used with integral or enum types. You can formally put an object of class type into a switch
statement, but that simply means that the compiler will look for a user-defined conversion to convert it to integral or enum type.
You can, creating an QStringList before iteration, like this:
QStringList myOptions;
myOptions << "goLogin" << "goAway" << "goRegister";
/*
goLogin = 0
goAway = 1
goRegister = 2
*/
Then:
It’s not possible to switch directly on strings in C++. However it’s possible in Qt using QMetaEnum
as shown here: Q_ENUM
and how to switch on a string
To do that, first declare an enum with the strings to be used in switch cases as enumerator name in your class declaration. Then add the enum to the metadata with Q_ENUMS
in order for the program to search later.
#include <QMetaEnum>
class TestCase : public QObject
{
Q_OBJECT
Q_ENUMS(Cases) // metadata declaration
public:
explicit Test(QObject *parent = 0);
enum Cases
{
THE, AT, IN, THIS // ... ==> strings to search, case sensitive
};
public slots:
void SwitchString(QString word);
};
Then in the .cpp
file implement the needed switch after converting the string to the corresponding value with .
The comparison is case sensitive so if you want a case insensitive search, convert the input string to upper/lower case first. You can also do other transformations needed to the string. For example in case you need to switch strings with blank spaces or unallowed characters in C/C++ identifiers, you may convert/remove/replace those characters to make the string a valid identifier.
void TestCase::SwitchString(QString word)
{
// get information about the enum named "Cases"
QMetaObject MetaObject = this->staticMetaObject;
QMetaEnum MetaEnum = MetaObject.enumerator(MetaObject.indexOfEnumerator("Cases"));
switch (MetaEnum.keyToValue(word.toUpper().toLatin1()))
// or simply switch (MetaEnum.keyToValue(word)) if no string modification is needed
{
case THE: /* do something */ break;
case AT: /* do something */ break;
case IN: /* do something */ break;
case THIS: /* do something */ break;
default: /* do something */ break;
}
}
Then just use the class for switching the strings. For example:
Does anyone know how one would be able to set a background color for the whole window of a Qt application?
So far I am using stylesheets but can only figure out how to assign a background color to a widget such as QGroupBox
or QPushButton
. Basically, if I want a black background how would I make it seamless without any borders of the original background?
I would simply use a Style Sheet for the whole window.
For instance, if your window is inheriting from QWidget, here is what I’m doing :
MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setStyleSheet("background-color: black;");
}
On my Mac, my whole application window is black (except the title bar).
EDIT : according to comment, here is a solution without using ui files and loading an external style sheet
#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtCore/QFile>
int main(int ArgC, char* ArgV[])
{
QApplication MyApp(ArgC, ArgV);
QMainWindow* pWindow = new QMainWindow;
QVBoxLayout* pLayout = new QVBoxLayout(pWindow);
pWindow->setLayout(pLayout);
QPushButton* pButton = new QPushButton("Test", pWindow);
pLayout->addWidget(pButton);
QFile file(":/qss/default.qss");
file.open(QFile::ReadOnly);
QString styleSheet = QLatin1String(file.readAll());
qApp->setStyleSheet(styleSheet);
pWindow->setVisible(true);
MyApp.exec();
}
The style sheet file (default.qss) is as follow :
This file is part of a resource file (stylesheet.qrc) :
And here is my project file :
This has worked for me:
Simply just add
to your code, you can give any color directly.
I’ve a QMap
object and I am trying to write its content to a file.
QMap<QString, QString> extensions;
//..
for(auto e : extensions)
{
fout << e.first << "," << e.second << '\n';
}
Why do I get: error: 'class QString' has no member named 'first' nor 'second'
Is e
not of type QPair
?
If you want the STL style with first
and second
, do this:
If you want to use what Qt offers, do this:
C++11 range-based-for uses the type of the dereferenced iterator as the automatically deduced “cursor” type. Here, it is the type of the expression *map.begin()
.
And since QMap::iterator::operator*()
returns a reference to the value (of type QString &
), the key isn’t accessible using that method.
You should use one of the iterator methods described in the documentation but you should avoid using
keys()
because it involves creating a list of keys and then searching the value for each key, or,
toStdMap()
because it copies all the map elements to another one,
and that wouldn’t be very optimal.
QMap::iterator
as the auto
type:
template<class Map>
struct RangeWrapper {
typedef typename Map::iterator MapIterator;
Map ↦
RangeWrapper(Map & map_) : map(map_) {}
struct iterator {
MapIterator mapIterator;
iterator(const MapIterator &mapIterator_): mapIterator(mapIterator_) {}
MapIterator operator*() {
return mapIterator;
}
iterator & operator++() {
++mapIterator;
return *this;
}
bool operator!=(const iterator & other) {
return this->mapIterator != other.mapIterator;
}
};
iterator begin() {
return map.begin();
}
iterator end() {
return map.end();
}
};
// Function to be able to use automatic template type deduction
template<class Map>
RangeWrapper<Map> toRange(Map & map)
{
return RangeWrapper<Map>(map);
}
// Usage code
QMap<QString, QString> extensions;
...
for(auto e : toRange(extensions)) {
fout << e.key() << "," << e.value() << '\n';
}
There is another wrapper here.
For people interested in optimizations, I have tried several approaches, did some micro benchmarks, and I can conclude that STL style approach is significantly faster.
I have tried adding integers with these methods :
And I have compared it with summing integers of a QList/QVector
Results :
Reference vector : 244 ms
Reference list : 1239 ms
QMap::values() : 6504 ms
Java style iterator : 6199 ms
STL style iterator : 2343 ms
Code for those interested :
#include <QDateTime>
#include <QMap>
#include <QVector>
#include <QList>
#include <QDebug>
void testQMap(){
QMap<int, int> map;
QVector<int> vec;
QList<int> list;
int nbIterations = 100;
int size = 1000000;
volatile int sum = 0;
for(int i = 0; i<size; ++i){
int randomInt = qrand()%128;
map[i] = randomInt;
vec.append(randomInt);
list.append(randomInt);
}
// Rererence vector/list
qint64 start = QDateTime::currentMSecsSinceEpoch();
for(int i = 0; i<nbIterations; ++i){
sum = 0;
for(int j : vec){
sum += j;
}
}
qint64 end = QDateTime::currentMSecsSinceEpoch();
qDebug() << "Reference vector : \t" << (end-start) << " ms";
qint64 startList = QDateTime::currentMSecsSinceEpoch();
for(int i = 0; i<nbIterations; ++i){
sum = 0;
for(int j : list){
sum += j;
}
}
qint64 endList = QDateTime::currentMSecsSinceEpoch();
qDebug() << "Reference list : \t" << (endList-startList) << " ms";
// QMap::values()
qint64 start0 = QDateTime::currentMSecsSinceEpoch();
for(int i = 0; i<nbIterations; ++i){
sum = 0;
QList<int> values = map.values();
for(int k : values){
sum += k;
}
}
qint64 end0 = QDateTime::currentMSecsSinceEpoch();
qDebug() << "QMap::values() : \t" << (end0-start0) << " ms";
// Java style iterator
qint64 start1 = QDateTime::currentMSecsSinceEpoch();
for(int i = 0; i<nbIterations; ++i){
sum = 0;
QMapIterator<int, int> it(map);
while (it.hasNext()) {
it.next();
sum += it.value();
}
}
qint64 end1 = QDateTime::currentMSecsSinceEpoch();
qDebug() << "Java style iterator : \t" << (end1-start1) << " ms";
// STL style iterator
qint64 start2 = QDateTime::currentMSecsSinceEpoch();
for(int i = 0; i<nbIterations; ++i){
sum = 0;
QMap<int, int>::const_iterator it = map.constBegin();
auto end = map.constEnd();
while (it != end) {
sum += it.value();
++it;
}
}
qint64 end2 = QDateTime::currentMSecsSinceEpoch();
qDebug() << "STL style iterator : \t" << (end2-start2) << " ms";
qint64 start3 = QDateTime::currentMSecsSinceEpoch();
for(int i = 0; i<nbIterations; ++i){
sum = 0;
auto end = map.cend();
for (auto it = map.cbegin(); it != end; ++it)
{
sum += it.value();
}
}
qint64 end3 = QDateTime::currentMSecsSinceEpoch();
qDebug() << "STL style iterator v2 : \t" << (end3-start3) << " ms";
}
Edit July 2017 : I ran this code again on my new laptop (Qt 5.9, i7-7560U) and got some interesting changes
Reference vector : 155 ms
Reference list : 157 ms
QMap::values(): 1874 ms
Java style iterator: 1156 ms
STL style iterator: 1143 ms
STL style and Java style have very similar performances in this benchmark
Is there any easy way to get the following work? I mean is there any helper class in Qt
which prepares the string for qDebug
?
No really easy way I am aware of. You can do:
or
You can use the following:
The nospace()
is to avoid printing out spaces after every argument (which is default for qDebug()
).
According to Qt Core 5.6 documentation you should use qUtf8Printable()
from <QtGlobal>
header to print QString
with qDebug
.
You should do as follows:
or shorter:
See:
I’m using Qt Creator, and this line is generated automatically by the Qt Creator:
#include <QtGui/QApplication>
But, why am I getting this message?
QtGui/QApplication: No such file or directory
Depending on the Qt-version (5) QtGui was moved to QtWidgets; so it becomes
You can try to add ‘declarative’ to the Project file:
then
It helps me
We have large project that used .NET Framework for showing forms/windows. Recently i decided to deprecate CLR dependency and move to Qt.
While learning Qt, we’ve migrated from Visual studio 2013 to 2015 and then i noticed that there is no qt support for MSVC 14 version which vs2015 use.
Additionally, Qt vs addin was not working jn visual studio express/community edition we use. Is there any chance for me to use Qt and qt addin in our projects?
Searching web did not help, and it looks like no one use Qt with latest Visual Studio?
As of now, you can just download Qt for Visual Studio 2015. Here.
You can use Qt in Visual Studio 2015 without any problems. As already stated in the comments, you have to build it from source but Qt is pretty straightforward to build. You can download the current (5.5) sources here and then follow this step by step example on building it.
I would also suggest reading more about the configure options, this might save you a lot of time. It might possibly save you some external dependencies as well if you skip components you do not need. My configuration for instance contains -skip qtwebkit -skip qtwebchannel
so I do not need ruby or python.
I could totally omit step 3 from the link. Just be sure to open the Visual Studio Command Prompt (32/64 is important here) for configure
and nmake
.
For Visual Studio 2015, the Qt Add-In is not available anymore. But there is an Extension (Tools > Extensions & Updates
) called Qt5Package or QtPackage which has the same functionality. After installing it, you have the Qt entry on your main toolbar where you have to specify a version and the path to the directory where you built it. This version will also be associated with the current project via the same menu.
If you load an existing project, you also have to convert it so the whole Qt functionality is used automatically. You can do this by opening the solution and right click on it; there should be an entry for the conversion to a QtAddin generated project.
I am using Qt 5.5 on Visual Studio 2015 with an old project and it is working without any issues.
Qt have finally added support for Visual Studio 2013 and 2015 although it’s only in beta right now. See QTVSADDINBUG-404 for progress and read the blog post From Visual Studio Add-In To Qt VS Tools (Beta).
I want to write a single, bold red line in my application using Qt.
As far as I understand, I would create a QLabel, set its textFormat to rich text and give it a rich text string to display:
QLabel *warning = new QLabel;
warning->setTextFormat(Qt::RichText);
warning->setText("{\\rtf1\\ansi\\ansicpg1252 {\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;} {\\colortbl;\\red255\\green0\\blue0;} \\f0 \\cf0 this is bold red text}");
I tested this rich text string in a rich text editor and it displays fine.
But Qt displays the whole string with all braces, keywords and backslashes instead of “this is bold red text”. What am I doing wrong?
Thank you for your help.
Try using HTML formatting: <b><font... etc </b>
.
Qt Designer does it like this: <span style=" font-size:8pt; font-weight:600; color:#aa0000;">TextLabel</span>
You can use Qt StyleSheets and set the styleSheet
property of QLabel
Qt supports most CSS styles on its QWidget
-derived classes. You don’t need to set the text format to Qt::RichText
for this to work.
Qt uses a simple HTML subset for formatting.
I have a problem with printing in Qt.
I have HTML code in QString variables. In this code I want to insert data from a database.
I get an error:
E:\apprendreQt\gestionstock6\vente.cpp:117: error: invalid operands of types
'const char*' and 'const char [27]' to binary 'operator+'
How can I fix this?
Here is my code:
int num_bl = ui->numeroBLlineEdit->text().toInt() ;
QString html;
QString requette = "select num_facture,date,nom,prenom,code_fiscale,designation,qte_out, prix,(qte_out * prix ) as Montant, sum(qte_out * prix) as Total from ventes join produits_en_ventes join clients join produits on ventes.vente_id = produits_en_ventes.vente_id and ventes.client_id = clients.client_id and produits_en_ventes.produit_id = produits.produit_id where ventes.client_id = :client_id ";
if(!m_db->isOpen())
QMessageBox::critical(this,tr("Inventoria Solution"),m_db->lastError().text()) ;
else{
m_query->clear();
m_query->prepare(requette);
m_query->bindValue(":client_id ", num_bl);
if(!m_query->exec())
QMessageBox::critical(this,tr("Inventoria Solution"),m_query->lastError().text()) ;
else{
html += " <table>"
"<thead>"
"<tr>"
"<th>N°</th>"
"<th>Désignation</th>"
"<th>Qte</th>"
"<th>Prix Unitaire</th>"
"<th>Montant</th>"
" </tr>"
"</thead>";
while(m_query->next())
{
int num_article = 1;
html += "<tr> <td>" + num_article + "</td> <td>"+m_query->value(5).toString()+"</td> <td>"+m_query->value(6).toInt() + "</td> <td>"+m_query->value(7).toInt() + "</td> <td>" + m_query->value(8).toInt() + "</td></tr>";
num_article++;
}
html += "<tfoot>"
"<tr>"
"<td>Total:"+ m_query->value(9).toInt()+"</td>"
"</tr>"
"</tfoot>"
"</table>";
}
print_Html(html);
}
If you use operator+
, you need to provide QString as an argument, but you use integer values instead: html += "<tr> <td>" + num_article
, where num_article
is declared as integer. You can replace it with, for example: QString::number(num_article)
. The same in this line:
should be replaced with
I’m not sure about your error. However, AFAIK a Qstring cannot be concatenated with an int as such.
int myInt = 0;
QString text = "someString" + myInt; // WRONG
int myInt = 0;
QString text = "someString" + QString::number( myInt ); // CORRECT
or
in Qt5 you can use the QStringLiteral
macro for each string that doesn’t need to be localized to transform all the string literals from const char*
(the C++ default) into QString, this will also make creation of those QStrings
cheaper (on compilers that support it)
for Qt4 you can use the QString(const char*)
constructor or QString::fromAscii(const char*)
static function
I designed a QMainWindow
with QtCreator's
designer. It consists of the default central widget (a QWidget
) which contains a QVBoxLayout
with all the other widgets in it. Now everything I want, is that the QVBoxLayout
automatically occupies the whole central widgets rectangle space.
How can I do this? I didn’t find any usable property neither in the central widgets properties nor the QVBoxLayout's
ones.
You don’t have to create a QVBoxLayout
manually. Just select your central QWidget
and press a make-layout button.
If you want to do it with code instead of using QtCreator
, you could set the layout in a QWidget
and then set the QWidget
as the central widget of the main window like this:
#include <QtGui>
#include <QWidget>
#include <QHBoxLayout>
#include "mainwindow.h"
MainWindow::MainWindow() {
// Set layout
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(myWidget1);
layout->addWidget(myWidget2);
// Set layout in QWidget
QWidget *window = new QWidget();
window->setLayout(layout);
// Set QWidget as the central layout of the main window
setCentralWidget(window);
}
Add at least one widget on your MainWindow
. Then select your window by clicking on it and click on the VerticalLayout
Button at the top of QTCreator
. You Vertical Layout is automatically added to the central widget and fills all the surface.
I’ve got an std::string content
that I know contains UTF-8 data. I want to convert it to a QString
. How do I do that, avoiding the from-ASCII conversion in Qt?
There’s a QString
function called fromUtf8
that takes a const char*
:
QString::fromStdString(content)
is better since it is more robust. Also note, that if std::string
is encoded in UTF-8, then it should give exactly the same result as QString::fromUtf8(content.data(), int(content.size()))
.
Usually, the best way of doing the conversion is using the method fromUtf8, but the problem is when you have strings locale-dependent.
In these cases, it’s preferable to use fromLocal8Bit. Example:
After watching many threads about getting selected rows numbers, I am really confused.
How do you get ROW numbers in QTableView
using QStandardItemModel
I used below selection model and behavior as
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
and if you have your own way of selecting can you explain how it works. Thanks for the help!
The method selectionModel()
return a QItemSelectionModel
.
You can use QItemSelectionModel
class to check/change/other selection(s)
Example:
Check selectedRows
method of the QItemSelectionModel
Class .
QModelIndexList selection = yourTableView->selectionModel()->selectedRows();
// Multiple rows can be selected
for(int i=0; i< selection.count(); i++)
{
QModelIndex index = selection.at(i);
qDebug() << index.row();
}
In Qt, When I add widgets to my layout, they are vertically centered by default. Is there a way to “List” the widgets from top to bottom instead of centering them vertically?
use void QLayout::setAlignment ( Qt::Alignment alignment )
method to set alignment according to your choice.
I find this a little more complicated than just using layout.setAlignment()
. It kept not working for me until just now, when I figured out that if you have expanding widgets that you set a maximum height for, then that widget will not be aligned the way you want.
Here is example code that does not top align the QTextBrowser()
widget even though I call layout.setAlignment(Qt.AlignTop)
. Sorry that it is in Python, but it is pretty easy to translate to C++ (I have gone the other way many times).
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyWidget(QWidget):
"""
Create a widget that aligns its contents to the top.
"""
def __init__(self, parent=None):
QWidget.__init__(self, parent)
layout = QVBoxLayout()
label = QLabel('label:')
layout.addWidget(label)
info = QTextBrowser(self)
info.setMinimumHeight(100)
info.setMaximumHeight(200)
layout.addWidget(info)
# Uncomment the next line to get this to align top.
# layout.setAlignment(info, Qt.AlignTop)
# Create a progress bar layout.
button = QPushButton('Button 1')
layout.addWidget(button)
# This will align all the widgets to the top except
# for the QTextBrowser() since it has a maximum size set.
layout.setAlignment(Qt.AlignTop)
self.setLayout(layout)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
widget.resize(QSize(900, 400))
app.exec_()
The following explicitly calls layout.setAlignment(info, Qt.AlignTop)
to get the expending text widget to work.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyWidget(QWidget):
"""
Create a widget that aligns its contents to the top.
"""
def __init__(self, parent=None):
QWidget.__init__(self, parent)
layout = QVBoxLayout()
label = QLabel('label:')
layout.addWidget(label)
info = QTextBrowser(self)
info.setMinimumHeight(100)
info.setMaximumHeight(200)
layout.addWidget(info)
# Uncomment the next line to get this to align top.
layout.setAlignment(info, Qt.AlignTop)
# Create a progress bar layout.
button = QPushButton('Button 1')
layout.addWidget(button)
# This will align all the widgets to the top except
# for the QTextBrowser() since it has a maximum size set.
layout.setAlignment(Qt.AlignTop)
self.setLayout(layout)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
widget.resize(QSize(900, 400))
app.exec_()
If you have a QVBoxLayout
and want your fixed size widgets to be stacked at the top, you can simply append a vertical stretch add the end:
If you have multiple stretchers or other stretch items, you can specify an integer stretch factor argument that defines their size ratio.
See also addStretch and addSpacerItem.
Not sure whether this answers your original question, but it is the answer to the one that I had when googling and being led to this page - so it might be useful for others too.
I am writing a Qt application on Windows using Visual Studio 2012. Using the Qt Add-in and a custom built static distribution of Qt 5.0.2. I am running into the dreaded "Failed to load platform plugin windows"
error whenever I run the application. I have added the following to the linker input:
At first I thought that maybe I should add “qwindowsd.lib” to that list as well however that did not fix the problem. What do I need to do in order to make my application run?
I solved it. Thanks to this I was able to get everything to work. I added the following libraries:
I also added the following to my code:
For dynamic build only: Make sure you move the qwindows.dll to the following directory:
Note that the plugins directory is missing! You put all the needed folders from QT_BASE/…/plugins/* directly together with your binaries. BTW: I did not need libEGL.dll, but my application almost has no GUI.
My source: http://qt-project.org/forums/viewthread/27056/#122588
I had the same error with MinGW version of Qt (not static): “Failed to load platform plugin windows”.
The solution for me was to add the DLLs libEGL.dll
and libEGLd.dll
.
I’m new to Qt, so I wonder whether there is a way to set the size of a QMainWindow
to (for example) 70% of the user’s desktop.
I tried the stretch factor but it didn’t work. QWidget::setFixedSize
worked but only with a pixel number, I think.
Thanks to Amir eas. The problem is solved. Here’s the code for it:
Somewhere in your QMainWindow constructor, do this:
resize(QDesktopWidget().availableGeometry(this).size() * 0.7);
This will resize the window to 70% of the available screen space.
You can use the availableGeometry(QWidget*)
method in QDesktopWidget
, this will give you the geometry of the screen that this widget is currently on.
For example:
QRect screenSize = desktop.availableGeometry(this);
this->setFixedSize(QSize(screenSize.width * 0.7f, screenSize.height * 0.7f));
Where this
is the MainWindow pointer. This will work when using multiple screens.