Background-image in Qt stylesheet doesn't work - c++

This should set the background to cats.jpg, but it doesn't do anything:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.setStyleSheet("background-image: url(images/ricepaper.png);");;
w.show();
return a.exec();
}
I thought that it could be a problem with the image location since changing the widget's background-color works fine, but the images folder is in the build-debug directory which I believe is the correct place. I've tried changing the image path, syntax, and styleSheet class and nothing has worked, any suggestions?

From Qt Style Sheets Reference:
It should work. Probably the image file is not to be found where the program expects. If you're using Qt Creator, you should be aware that it builds the target binary in a separate directory (usually with a name like build-yourprojectname-qtversion-Debug or so). That's called shadow build.
You'll need to copy over your image(s) to the proper location relative to that shadow build directory, otherwise the program will not be able to find the file.
Your best bet is to embed the image in the binary as a resource.
I just tried this and seems to be working for me:
In main.cpp:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *w = new QWidget;
w->setStyleSheet("background-image: url(:/resources/pixmaps/close.png);");
w->show();
return app.exec();
}
Note the :/ part in url(:/resources/pixmaps/close.png). That's needed for embedded resources.
In resources.qrc:
<RCC>
<qresource prefix="/">
<file>resources/pixmaps/close.png</file>
... other resource files go here
</qresource>
At the end of testproject.pro:
RESOURCES += \
resources.qrc
Of course you'll need to put the images in the proper location in your project directory so that the resource compiler can find it.
In my example,
resources/
├── pixmaps
│   ├── application.png
│   ├── cancel.png
│   ├── close.png <--Here
...

Related

Reading file from working directory QtWebEngine

Hello I am trying to set the QWebEngine URL to an index.html file that is placed in the working directory.
I am trying to use the file by setting the URL to ./index.html but it cant seem to find the file.
Here is where my files are placed
content (Work directory)
main.cpp
content.pro
index.html
How can i open index.html through the QWebEngine without using the full system path?
here is my code
#include <QApplication>
#include <QWebEngineView>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QWebEngineView view;
view.setUrl(QUrl(QStringLiteral("file:///./index.html")));
view.resize(1024, 750);
view.show();
return app.exec();
}
Try moving the html file to your project build directory (you're currently keeping it inside the source directory). Then you can build your URL this way:
QUrl url = QUrl::fromLocalFile(QDir::currentPath() + "/index.html");
and set it to the view:
QWebEngineView view;
view.setUrl(url);
view.resize(1024, 750);
view.show();
From http://doc.qt.io/qt-5/qurl.html
qDebug() << QUrl("main.qml").isRelative(); // true: no scheme
qDebug() << QUrl("qml/main.qml").isRelative(); // true: no scheme
qDebug() << QUrl("file:main.qml").isRelative(); // false: has "file" scheme
qDebug() << QUrl("file:qml/main.qml").isRelative(); // false: has "file" scheme
Try: view.setUrl(QUrl(QStringLiteral("index.html")));
As p-a-o-l-o pointed out in his answer, you're likely building out-of-source, so your index.html file has to be in the folder where content.exe is created, not in the source folder.
To make this less complicated, and safer, Qt supports embedding files in the .exe via Qt Resource files (.qrc). These can easily be created in Qt Creator, and once added to the project, the embedded files are accessed via a qrc:/// prefix.
So in your sample code, after adding a .qrc file to your project and adding index.html to it, you would adjust your code like this:
view.setUrl(QUrl(QStringLiteral("qrc:///index.html")));
This has the advantage of working regardless of build type or location, and it's a lot simpler than trying to add a file copy step to your project file (or to manually copy the file each time)

QT 5.4, Unable to access Resource from code

I try to include style images of my app into a q-resource file.
When I include the file directly in the code, it work, but when i try to use QResource, it fail (do not load the file).
I have the resource file in the main directory:
AppFolder
|- main.cpp
|- darkstyle.qrc
|- darkstyle
|- WindowTitleBar.png
The following example print:
failed1
failed2
#include <QApplication>
#include <QResource>
#include <Qfile>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
bool ok= QResource::registerResource("darkstyle.qrc");
if (!ok) qDebug()<<"failed1";
QFile file(":/darkstyle/WindowTitleBar.png");
//QFile file("../AppFolder/darkstyle/WindowTitleBar.png"); //that work
if(!file.open(QFile::ReadOnly | QFile::Text)) qDebug()<<"failed2";
else file.close();
//return a.exec();
return 0;
}
Note: Qt creator by default create binaries (.exe) in a top folder: ../build-AppFolder_Qt_5_4_1_MSVC2013_64bit-Debug/debug/AppFolder.exe
The execution root path seem to be: ../build-AppFolder_Qt_5_4_1_MSVC2013_64bit-Debug
I tried most of possible combinations with execution paths.
Note2: Some examples use a .rcc file format, I have none of these, but that could be a clue.
Summary:
How to access a QResource file from inside a QT app?
EDIT 1: Content of qrc file:
<RCC>
<qresource prefix="/">
<file>darkstyle/WindowTitleBar.png</file>
<file>darkstyle/WindowTitleButton.png</file>
<file>darkstyle/WindowTitleButton1.png</file>
<file>darkstyle/WindowTitleButton2.png</file>
<file>darkstyle/WindowTitleButton3.png</file>
</qresource>
</RCC>
QResource::registerResource("darkstyle.qrc") registers the resource description. If you want to use resources dynamically like this you need to register the compiled resources themselves. Run rcc -binary darkstyle.qrc -o darkstyle.rcc and use QResource::registerResource("darkstyle.rcc")
Alternatively, compile the resources into your binary directly. Do do so, use RESOURCES += darkstyle.qrc in your .qrc, and leave out the QResource::registerResource.
The problem is related to an incompatibility of the given version of QT with MSVS2013.
The problem is solved by downloading another version of QT or visual studio.

Confusion QLabel and QPixmap

I want to display a Pixmap into a Label on Qt.
Here is the problem, the above code doesn't display the image that I want.
Please correct me if something is wrong. I have checked again and again (even it's few lines) but it didn't lead to results!!!
QLabel *label;
label= new QLabel(this);
QPixmap jet("C:/images/image.jpg");
label->setPixmap(jet);
One other problem, it seems that it works in another machine!
By default, qt builds with “-system-libjpeg”, so sudo apt-get install libjpeg if you are on linux, and to check supporting image formats, add
qDebug() << QImageReader::supportedImageFormats ();
to add plugins to your project, go to QtSDK/Desktop/Qt/4.8.1/gcc/plugins or something like this, chose the version you use, and copy "plugins" folder to root of your project(more precisely - you need only "imageformats" folder, that lays within plugins), and in your main.cpp file add line addLibraryPath (by the way, plugin's folder contain not only dlls for release, but for debugging also, they are a bit heavy, so i would remove dlls with *d.dll, for example QtCore.dll - for release, QtCored.dll - for debugging)
QApplication a(argc, argv);
MainWindow w;
a.addLibraryPath("plugins");
w.show();

Does Meego Nokia N950 support C++ QML binding?

I want to communicate between C++ and QML on Meego. It happens using C++ QML binding as described in this link.
When I run an app on the Symbian platform it works, and data from C++ is available to manipulate in some QML file.
But on Meego it always says myItem.qml file not found.
See the following code snippet:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDeclarativeView view;
MyClass myClass;
view.rootContext()->setContextProperty("myObject", &myClass);
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();
return app.exec();
}
Does Meego does not support QML C++ binding?
I also tried to give the exact path of the QML file but never found that file, even myItem is in project structure.
Is there some thing associated with path settings in .pro file etc
Please help on this as I am stuck here with this and cannot move forward in my app using Qt Quick.
Yes, but your problem isn't related to C++ and QML bindings. Your application (specifically the view) can't find the .qml file to load.
By default, I think on meego the default path to look in is ../qml. So by default you should be packaging into /opt/YOURNAME with the binary in /opt/YOURNAME/bin and the qml files in /opt/YOURNAME/qml.
However, you can also put the qml files into a resource and use the :/ paths to access a resource instead.
IE, in your resource file:
<RCC>
<qresource prefix="/">
<file>qml/foo.qml</file>
</qresource>
</RCC>
And in C++:
viewer.setSource(QUrl("qrc:/qml/foo.qml"));

Qt - QWidget: Cannot create a QWidget when no GUI is being used

I'm trying to run a simple Qt program, and when doing so, I get a console window mentioning: QWidget: Cannot create a QWidget when no GUI is being used, and the second line This application has requested the Runtime to terminate....., and the .exe file thus stops working.
My .pro file looks as follows:
#-------------------------------------------------
#
# Project created by QtCreator 2011-04-02T07:38:50
#
#-------------------------------------------------
QT += core
QT += gui
TARGET = Hello
CONFIG += console
CONFIG += qt
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
Any ideas on that?
Thanks.
The problem is not with this .pro; it is most likely in main.cpp. Qt requires you to create a QApplication before creating any QWidget subclasses (as well as certain other classes, such as QPixmap). Your main function should begin with the line:
QApplication app(argc, argv);
and will probably end with a line like:
return app.exec();
In between these calls, you should create and show your main window.
I found that you can do it with a Qt Console project, but ofcourse it will not have the functionality of a console program when you are done with my edits.
First of all you need to exchange #include <QtCoreApplication> with #include <QApplication> in your main.cpp (where you start your application)
In the main(int,char**){
exchange QCoreApplication a(argc, argv); with QApplication a(argc, argv);
and in between QApplication and return a.exec you have your widget and other gui related stuff
and in the end you use return a.exec();}
I think I found where the issue is.
Since I'm using Qt Creator, and when creating a new project, I was choosing Qt Console Application instead of Qt Gui Application.
"QWidget: Cannot create a QWidget when no GUI is being used" happens when you application isn't QApplication instance.
From Qt docs:
QApplication specializes QGuiApplication with some functionality
needed for QWidget-based applications. It handles widget specific
initialization, finalization, and provides session management.
For any GUI application using Qt, there is precisely one QApplication
object, no matter whether the application has 0, 1, 2 or more windows
at any given time. For non-QWidget based Qt applications, use
QGuiApplication instead, as it does not depend on the QtWidgets
library.
From the docs,
the QApplication class manages the GUI application's control flow and main settings whilst
the QCoreApplication class provides an event loop for console Qt applications
I had the same problem, the default QT Console App uses the QCoreApplication instead of the QApplication to run the application.
Here is what i did to make it work
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget widget;
widget.show();
return a.exec();
}
And i did not change anything in my project file
QT += core
QT += gui
TARGET = Layouts
CONFIG += gui
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp