First time using Qt: How to display an image? - c++

Noob: How to display an image
I am very new to this, just starting actually. I need to figure out how to display an image on screen.
First I tried:
Source code:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QPixmap qp = QPixmap("../images/tank2.bmp");
if(qp.isNull())
{
printf("Yes its null\n");
}
else
{
QGraphicsPixmapItem item(QPixmap("../images/tank2.bmp"));
scene.addItem(&item);
}
view.show();
return a.exec();
}
from:
Qt jpg image display
it compiles and runs but doesn't show an image. returns 0, etc.
Then I just sorta messed around from there. I'm also curious about something: In Qt editor they show a file structure that doesn't exist on the disk. They have files "Headers", "Sources", and Resources whereas on the systems its just a folder "projectname" with all the files in one folder. Is this just for visual clarity?
The version of QtCreator I'm using is 2.4.1 running Qt 4.7.4 64 bit.
My eventual goal is to make a widget where a picture is a clickable icon where you select that pic and can place it on a larger screen like a tile.
Another Question: Why does Qt have things like "QString" and "QChar"? Is there something wrong with the normal c++ libraries?

If you just want to display a simple image then make a Qlabel the central widget and call setPixmap() passing it your image path
"Another Question: Why does Qt have things like "QString" and "QChar"?
Is there something wrong with the normal c++ libraries?"
Yes there is lots wrong with the normal libraries - at least for std::string.
When Qt was started there wasn't very good cross platform STL support and the standard libraries were very bad at Unicode and support for translations. QString doesthis very well - although I think a combination of modern STL and boost can probably do everything QString can do.
Almost all of the Qt types are automatically reference counted so you can pretty much ignore memory management for them AND pass them around freely. There are also some tricks Qt can do because the extra MOC compile pass means it has Java-like introspection that standard C++ doesn't.
But in general you are free to use standard C++ types (Qt: Qt classes vs. standard C++)

Tested like this, it works. Don't forget to create qrc file.
#include <QtGui/QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include "mainwindow.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QPixmap qp = QPixmap(":/images/123.bmp");
if(qp.isNull())
{
printf("Yes its null\n");
}
else
{
printf("HAHA");
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(QPixmap(":/images/123.bmp"));
scene.addItem(item);
}
view.show();
return a.exec();
}
Here are qrc file:
<RCC>
<qresource prefix="/">
<file>images/123.bmp</file>
</qresource>
</RCC>
And .pro file
QT += core gui
TARGET = testimage
TEMPLATE = app
SOURCES += main.cpp
RESOURCES += 123.qrc

I think your problem is here:
{
QGraphicsPixmapItem item(QPixmap("../images/tank2.bmp"));
scene.addItem(&item);
}
item goes out of scope before you'll actually use it.
I'm also pretty sure you meant that to use the QPixmap that you loaded earlier at the top-level scope.
Generally speaking, you want to limit your questions on SO to a single question... but to address your last question: QChar and QString allow the Qt libs to make several assumptions about strings. The most obvious of which is that QStrings have a standardized encoding.

Related

Is it possible to add background image on QWidget without using QtCreator?

Having trouble adding background image on the widget, even though I referenced the recent codes online.
This is my current code for main.cpp:
#include <QApplication>
#include <QWidget>
int main (int argc, char **argv){
QApplication app (argc,argv);
QWidget *w=new QWidget();
w->setStyleSheet("background-image: url(:/cover.jpg);");
w->setWindowTitle("Test");
w->show();
return app.exec();
}
After executing the code, how come the widget remains blank? Thanks in advance!
QtCreator is an IDE designed by Qt. It's just an interface.
I checked your implementation and I don't see anything wrong. It also work well on my pc. Can you check your image url or try with another image ?
Btw, if you're on linux, try removing : character after url ;
w->setStyleSheet("background-image: url(/cover.jpg);");
EDİT:
If jpg is in the same directory with your application, it should be ;
w->setStyleSheet("background-image: url(./cover.jpg);");
You can give a full path to avoid this kind of errors.
"Is it possible to add background image on QWidget without using QtCreator?"
Yes, of course it is.
QtCreator is just an IDE. You don't need to use it at all to write code using the Qt library.
Just as you can use it to write code that does not use Qt at all.

Using QPainter with QCoreApplication

We have an application (QCoreApplication) that takes some images as input, does something to them, and exports them again. We now need to add some text to the images, and tried to do this with the QPainter class. It all worked well when using it in one of our other apps (using QApplication), but not in our main QCoreApplication app.
Here is the code:
void drawTextOnImage(QImage* image, const QString& text, const QFont& font)
{
QPainter p;
if (!p.begin(image)) return;
p.setFont(font);
p.drawText(image->rect(), Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, text);
p.end();
}
The application crashes on the drawText line.
Any ideas?
It is a very simple text, so suggestions without using Qt will also be appreaciated.
When using classes from "Qt Gui" like QPainter, you are supposed to use a QGuiApplication, not a QCoreApplication.
You might get lucky and be able to make some GUI stuff works while using only a QCoreApplication. But as you have discovered, it makes your application very brittle. Some classes like QPixmap will print an error message, but others will just crash.
The same is applicable with "Qt Widget": if you use a widget related class, you must use a QApplication.
Note that since QApplication inherits QGuiApplication, if you have a QApplication you can use "Qt Gui".
In case you need to run a non-GUI application on something without a windowing system, you need, aside from creating an instance of QGuiApplication, to also choose an appropriate Qt platform.
For me, offscreen platform worked fine. I was generating images with textual elements and saving them to files on a headless Raspberry Pi. My code then was like the example below. Note that setenv is a POSIX function and may need a replacement on Windows, though I'm not sure whether windowless Windows is a thing at all.
#include <stdlib.h>
#include <QImage>
#include <QPainter>
#include <QGuiApplication>
int main(int argc, char** argv)
{
setenv("QT_QPA_PLATFORM","offscreen",1);
QGuiApplication app(argc,argv);
QImage img(128,128, QImage::Format_RGB888);
img.fill(Qt::white);
QPainter p(&img);
p.drawText(QPoint(0,64), "Works!");
img.save("/tmp/test.png");
}

QTreeView no show when placed inside QDockWidget

I want to show a file system using QTreeView on a QDockWidget. The tree will be dynamically changed, so I decided to use QTreeView instead of QTreeWidget.
Here is my code:
QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
TreeModel model(file.readAll());
file.close();
QTreeView w;
w.setModel(&model);
swatch1->setWidget(&w);
w.setEnabled(true);
addDockWidget(leftarea, swatch1);
swatch1 is of type QDockWidget. The above code is inside a function body of type (inherited from) MainWindow. The code runs smoothly, and the tree does not show up.
I also tried another way: putting QTreeView into a QVBoxLayout (using setWidget method), which in turn be put into a QDockWidget (using setLayout method). This 2nd code also runs smoothly, and the tree does not show up.
This code is copied from a working example on Qt Creator IDE, and I tested it working. The only difference is, in the original QTreeView example, the above code is placed inside the main() { ..... } function.
Does anyone has a working example, putting QTreeView into QDockWidget and working (the code actually shows the tree)? Thanks in advance.
I'm not quite sure what went wrong in the OP. However, I made a minimal complete sample to see whether there are pitfalls:
// standard C++ header:
#include <iostream>
#include <string>
// Qt header:
#include <QApplication>
#include <QDockWidget>
#include <QFileSystemModel>
#include <QMainWindow>
#include <QTreeView>
using namespace std;
int main(int argc, char **argv)
{
cout << QT_VERSION_STR << endl;
// main application
#undef qApp // undef macro qApp out of the way
QApplication qApp(argc, argv);
// setup GUI
QMainWindow qWin;
QDockWidget qDock;
qDock.setAllowedAreas(Qt::AllDockWidgetAreas);
QTreeView qTreeView;
QFileSystemModel qFSModel;
qTreeView.setModel(&qFSModel);
QString path = QDir::currentPath();
QModelIndex indexPath = qFSModel.index(path);
qTreeView.scrollTo(indexPath);
qDock.setWidget(&qTreeView);
qWin.addDockWidget(Qt::TopDockWidgetArea, &qDock);
qWin.show();
// run application
return qApp.exec();
}
Compiled and tested it with VS2013, Qt 5.6 on Windows 10 (64 bit):
As can be seen in the snapshot, the QTreeView is visible (docked and undocked). I checked that both re-act on mouse clicks - they did.
(I guess this is one of my most minimal Qt applications I ever wrote.)
Scheff,
Thank you very much for your answer. Sorry I may not be clear about what I am asking: the tree become visible when this code section is in the main() { ....} function:
QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
TreeModel model(file.readAll());
file.close();
QTreeView w;
w.setModel(&model);
w.show();
But the same code (almost same) does not working (program runs but the tree is not visible) when this section of code is in a class function inside MainWindow and QTreeView is added to a QDockWidget:
QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
TreeModel model(file.readAll());
file.close();
QTreeView w;
w.setModel(&model);
swatch1->setWidget(&w);
addDockWidget(leftarea, swatch1);
here, leftarea is a Qt:DockWidgetArea, and swatch1 is an object of type inherited from QDockWidget. when run this program, swatch (a QDockWidget) is visible, but not the tree. still struggling ...
The problem solved. The original code I wrote by itself is correct, but it is in an object method, and as soon as the execution leaves the object, the tree is destroyed.
So, it is a C++ variable scoping problem, not exactly a Qt problem. I have been using python for a while, and just switch back to C++.
Scheff, thank you for your posting confirmed to me that the Qt code is correct, and suggests to me that something else is wrong.

How to set an application icon in Qt

I have some trouble trying to set an icon for my QT application.
The icon is named "room.ico" and is on the same directory as the source file.
Here is the code :
#include <QApplication>
#include <QWidget>
int main( int argc, char *argv[ ] )
{
QApplication app( argc, argv) ;
QWidget fenetre;
fenetre.setWindowIcon(QIcon("room.ico")); // Nothing happens
fenetre.setWindowTitle("Heloo");
fenetre.show();
return app.exec() ;
}
I have tried to add win32:RC_ICONS += room.ico in the .pro file but that didn't work. I have also tried "./room.ico" but still no icon.
I have tried to use this :
QPixmap pixmap = QPixmap ("room.ico");
fenetre.setWindowIcon(QIcon(pixmap));
And guess what !!! it didn't work ... i'm just a newbie to QT :p
Any suggestions will be appreciated , thanks
QT's documentation for QWindow::setWindowIcon should be what you need.
Make an icon file (you appear to have done this already: room.ico
Add your icon file to a QT resource file (.qrc or .rc) which you should add to your project (the documentation discusses how to do this
Use setWindowIcon and pass in a QIcon:
app.setWindowIcon(QIcon(":/room.ico")); (this assumes your file is in the resource file)
Your problem appears to be that you didn't prepend :/ when passing in the filename to QIcon.

QT HTML5 with Menu Bar like real program

I'm working on an QT HTML5 application and I was wondering how i could add an top menu just like normal program ( with the default file, tools, help... options ).
I think that I've to change something in the html5applicationviewer.cpp, but I've got 0 knowledge of that ( I'm learning this... )
Even if you could point me a little bit in the right direction, I'm grateful. I've searched around, but found absolutely nothing about this topic ( but maybe i didn't search right... )
If you need more info, please ask.
Simplest way to add normal "desktop"-style menus to a Qt app is to use QMainWindow which has good support for menus.
Here's something to get you started. First I created the default HTML5 Qt application with Qt Creator (SDK version 5.2.1). Then I edited the main.cpp and added some lines. Result is below, original lines without comment and all added lines with comment.
#include <QApplication>
#include <QMainWindow> // added
#include <QMenuBar> // added
#include <QMenu> // added
#include <QAction> // added
#include "html5applicationviewer.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow w; // important, viewer is in stack so w must be before it!
Html5ApplicationViewer viewer;
w.setCentralWidget(&viewer); // set viewer as the central widget
QMenu *fileMenu = w.menuBar()->addMenu("&File"); // create file menu
QAction *exitAction = fileMenu->addAction("&Exit"); // create exit action
QObject::connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); // make the action do something
viewer.setOrientation(Html5ApplicationViewer::ScreenOrientationAuto);
//viewer.showExpanded(); // will be shown by main window
viewer.loadFile(QLatin1String("html/index.html"));
w.show(); // show main window
return app.exec();
}