Open Seally opened 10 years ago
Really? Have you added QT += widgets
in the .pro file?
The problem isn't whether or not I can get the example to work (I can), but I find the wording to be problematic because:
#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QScopedPointer<QWidget> widget(new CustomWidget());
widget->resize(240, 120);
widget->show();
return app.exec();
}
#include <QtGui>
is useless here in the case of Qt 5 as QApplication is now part of QtWidgets and not of QtGui anymore. All of QApplication's dependencies are already included in the header file, and unless one uses them explicitly as well, it is simply not recommended to add them. #include <QApplication>
is a far better option and will actually compile after customwidget.h is also included.#include "customwidget.h"
line at the top could clarify a couple of things and prevent some headscratches. It's fine to leave this line out after a couple more examples but I find this to be too early.CustomWidget widget;
could just as easily replace this entire line with some ->
to .
replacements in the later lines.Now that you mention it, it would also be nice to mention the QtWidgets module separation from QtGui during the Qt 4->5 transition* and that the line greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
(or the slightly less portable QT += widgets
) can used to remedy "QWidget not found" and similar errors. I won't rely on the IDE to put this in for me. I still remember myself a couple of years back spending ages trying to find why my program will compile in Qt 4 but not in Qt 5 after I tried to recreate the .pro file according to what I knew about it at the time. Not an event I'd like to see anyone repeat.
*Since I'm mostly skimming these parts, this may have already been mentioned without me noticing.
Since the section instructs the reader to use Qt 5, the example given under 'Widget Application' is incorrect (but is correct for Qt 4). QWidget has been moved to QtWidgets in Qt 5 and merely including QtGui will not allow this code to compile.
Also, you can just simply put QWidget on the stack instead of bothering with QScopedPointer (or std::unique_ptr and similar smart pointers) as it will be automatically destroyed anyway.
The correct code should be somewhere along the lines of:
In the next example,
#include <QtWidgets>
is highly NOT recommended as a header file include as it will make the resulting binary gigantic for no good reason. Breaking this into:is a much better solution.
Later examples should forward declare classes (if possible) or add additional
#include
s as needed so readers won't supersize their binaries.On a completely unrelated note: I hope QMLBook is not abandoned yet. It's a great primer to QML, despite its flaws.
back-link: ch02/index.html#widget-application