qt quick 2 printing with console - qt

I can't figure out how to print with console.log inside a qt quick application.
I have this .pro file:
TEMPLATE = app
QT += qml quick
CONFIG += c++11
CONFIG += console
SOURCES += main.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Default rules for deployment.
include(deployment.pri)
this is main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
this is main.qml:
import QtQuick 2.5
import QtQuick.Window 2.0
Window {
visible: true
Text {
anchors.centerIn: parent
text: "Hello World"
}
Component.onCompleted: console.log("foo")
}
Why it doens't print "foo"?

solved it was caused by the fact that Fedora has *.debug=false inside /etc/xdg/QtProject/qtlogging.ini and that prevents the messages to be printed. To "solve" this it's enough to create the file ~/.config/QtProject/qtlogging.ini with this content:
[Rules]
default=true

Related

Why Qt Quick Application couldn't dynamically create a control by the Method Qt.createComponent

In my Qt Quick Application, I wanna use Qt.createComponent to create component dynamically——the effect I expect: when I click the button"create checkbox" ,the window will create a CheckBox dymamically
I made it in a Qt Quick UI prototype(qml-only project),but failed in the Qt Quick Application
After running the app, I click the button"create checkbox" many times, but the window has no response and the program stuck
// app.pro
QT += quick
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Refer to the documentation for the
# deprecated API to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
// CheckBox.qml
import QtQuick 2.0
import QtQuick.Controls 2.12
CheckBox{
text: "checkcheck"
}
//main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
Window {
id:root
visible: true
width: 200
height: 200
title: qsTr("Hello World")
Button{
text: "create checkbox"
anchors.centerIn:parent
onClicked: loadCheckBox(root)
}
function loadCheckBox(parent){
var obj=Qt.createComponent("CheckBox.qml");
if(obj.status==Component.Ready){
var checkBox=obj.createObject(parent)
}
}
}
My environment: Win10 QtCreator Qt5.13.2_MSVC2017_64bit
Anyone knows how to modify it?

QSystemTrayIcon not available then run application with sudo on Ubuntu 18.04 LTS

QSystemTrayIcon not available in application if run with sudo. How can this problem be solved?
./qsystemtrayicontest - the tray icon is available
sudo ./qsystemtrayicontest - the tray icon is not available
output
QML debugging is enabled. Only use this in a safe environment.
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'
ERROR: No native SystemTrayIcon implementation available.
Qt Labs Platform requires Qt Widgets on this setup.
Add 'QT = widgets' to .pro and create QApplication in main().
qml: SystemTrayIcon::available false
Below is a minimal example with a qml interface. But on ordinary widget error is repeated in the same way.
qsystemtrayicontest.pro
QT += quick
CONFIG += c++11
QT += widgets
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
main.cpp
RESOURCES += qml.qrc
QML_IMPORT_PATH =
QML_DESIGNER_IMPORT_PATH =
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import Qt.labs.platform 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Text {
anchors.centerIn: parent
text: "SystemTrayIcon::available: " + idSystemTrayIcon.available
}
SystemTrayIcon {
id: idSystemTrayIcon
visible: true
Component.onCompleted: {
console.log("SystemTrayIcon::available", available)
}
}
}

View PDF in QML WebView

I would like to view a PDF file in a WebView created in my QML code. I am importing QtWebView 1.1 and setting the url property to the path of the PDF file but I am getting this error:
[13044:12820:0314/144814.854:ERROR:in_progress_cache_impl.cc(192)]
Cache is not initialized, cannot RetrieveEntry.
[13044:12820:0314/144814.854:ERROR:in_progress_cache_impl.cc(176)]
Cache is not initialized, cannot AddOrReplaceEntry.
[13044:12820:0314/144814.854:ERROR:in_progress_cache_impl.cc(192)]
Cache is not initialized, cannot RetrieveEntry.
When I use the same code to view an image it works. This question: Display PDF file with QWebView is close to what I want but QML does not seem to give me access to the settings method the way that C++ does (WebView docs). Is there some other way to do this?
It seems that you are confusing elements, QWebView belongs to QtWebkit (uses Webkit) that no longer exists in Qt and that was replaced by Qt WebEngine (uses chromium). And another thing is WebView of Qt WebView that uses the native APIs (for example Android does not support Qt WebEngine but if WebView).
Qt WebEngine and Qt WebView does not support PDF visualization (Qt WenEngine will support it very soon) natively so a solution is to use some js library that does it as PDF.js so that is the alternative that I propose in base to an old answer.
*.pro
QT += quick webview
CONFIG += c++11
SOURCES += main.cpp
RESOURCES += qml.qrc
COPY_CONFIG = 3rdParty example.pdf
copy_cmd.input = COPY_CONFIG
copy_cmd.output = ${QMAKE_FILE_IN_BASE}${QMAKE_FILE_EXT}
copy_cmd.commands = $$QMAKE_COPY_DIR ${QMAKE_FILE_IN} ${QMAKE_FILE_OUT}
copy_cmd.CONFIG += no_link_no_clean
copy_cmd.variable_out = PRE_TARGETDEPS
QMAKE_EXTRA_COMPILERS += copy_cmd
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtWebView>
class PDFJS: public QObject
{
Q_OBJECT
Q_PROPERTY(QString version READ version WRITE setVersion NOTIFY versionChanged)
QString m_version;
public:
QString version() const{
return m_version;
}
void setVersion(QString version){
if (m_version == version)
return;
m_version = version;
Q_EMIT versionChanged(m_version);
}
Q_SIGNAL void versionChanged(QString version);
Q_INVOKABLE QUrl getUrl(const QUrl & path){
QString pdfjs_path = QDir::current().filePath(QString("3rdParty/pdfjs-%1-dist/web/viewer.html").arg(m_version));
QUrl pdf_url = QUrl::fromLocalFile(pdfjs_path);
QUrlQuery query;
query.addQueryItem("file", path.toString());
pdf_url.setQuery(query);
return pdf_url;
}
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QtWebView::initialize();
QQmlApplicationEngine engine;
PDFJS pdfjs;
engine.rootContext()->setContextProperty("applicationDirPath", QGuiApplication::applicationDirPath());
engine.rootContext()->setContextProperty("PDFJS", &pdfjs);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
#include "main.moc"
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtWebView 1.1
Window {
visible: true
width: 640
height: 480
title: qsTr("PDFJS Example")
WebView{
id: webview
anchors.fill: parent
}
Component.onCompleted:{
PDFJS.version = "2.1.266"
webview.url = PDFJS.getUrl("file://" + applicationDirPath + "/example.pdf")
}
}
You can find the complete project here
Update: only QML
.
|-- 3rdParty
| `-- pdfjs-2.1.266-dist
|-- example.pdf
`-- main.qml
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtWebView 1.1
Window {
visible: true
width: 640
height: 480
title: qsTr("PDFJS Example")
WebView{
id: webview
anchors.fill: parent
}
Component.onCompleted:{
var pdfjs_path = Qt.resolvedUrl("3rdParty/pdfjs-2.1.266-dist/web/viewer.html")
var path = Qt.resolvedUrl("example.pdf");
var url = pdfjs_path + "?file=%1".arg(path)
console.log(url)
webview.url = url
}
}
This part of the project you find here
Another option to this problem is to look into the Poppler Library. This library can be used to convert a page in a PDF to an image. Take a look into the Poppler::Page object's renderToImage. The image can then be displayed on a QQuickPaintedItem. Hope this helps someone.

QML import QtCharts module error

When I try to import the QtCharts module to my QML files y always get the same warning message:
"found not working imports: file: C:/.... module "QtCharts" is not
installed"
I'm using OpenSource QtCreator 4.0.3 with Qt 5.7.0.
I have the folder QtCharts in the path: C:\Qt\5.7\mingw53_32\qml
I've also included the folder path using the property in the .pro file:
QML2_IMPORT_PATH: C:\Qt\5.7\mingw53_32\qml
What am I missing?
Here is a simple test code:
// QtChartsTest.pro
TEMPLATE = app
QT += qml quick
QT += charts
CONFIG += c++11
SOURCES += main.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules in Qt Creator's code model
QML2_IMPORT_PATH = C:\Qt\5.7\mingw53_32\qml
# Default rules for deployment.
include(deployment.pri)
// Main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
// Main.qml
import QtQuick 2.7
import QtQuick.Window 2.2
import QtCharts 2.1
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
}
I was stuck on a similar issue and was frustrated by Qt's documentation on the subject, so I'll put my method of solving my own issues here for posterity.
I'm not sure of the exact cause of your issue, but I can offer you a suggestion to try and troubleshoot it.
In your main.cpp add the following line.
qDebug()<<engine.importPathList();
So your main will be
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QDebug>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qDebug()<<engine.importPathList();
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
This will include the complete list of include paths. If you do not see the include path listed there you can add it by adding the following line:
engine.addImportPath(directory);
where "directory" is a QString to the include directory.
My understanding is that the QML2_IMPORT_PATH variable only applies at run time, and not at compile time, which means that QtCreator does not see the path when it compiles. engine.addImportPath(directory); on the other hand adds the path prior to starting the qml engine, (and thus the first qml import statements)
I am not saying this is the best way to solve your issue, but it did help me solve my issue.
int main(int argc, char *argv[])
{
// Qt Charts uses Qt Graphics View Framework for drawing, therefore QApplication must be used.
QApplication app(argc, argv);
QQuickView viewer;
// The following are needed to make examples run without having to install the module
// in desktop environments.
#ifdef Q_OS_WIN
QString extraImportPath(QStringLiteral("%1/../../../../%2"));
#else
QString extraImportPath(QStringLiteral("%1/../../../%2"));
#endif
viewer.engine()->addImportPath(extraImportPath.arg(QGuiApplication::applicationDirPath(),
QString::fromLatin1("qml")));
//***** [Solve] FORCE THE MODULE TO BE IMPORTED.
QObject::connect(viewer.engine(), &QQmlEngine::quit, &viewer, &QWindow::close);
qDebug() << viewer.engine()->importPathList();
viewer.setTitle(QStringLiteral("QML Axes"));
viewer.setSource(QUrl("qrc:/qml/qmlaxes/main.qml"));
viewer.setResizeMode(QQuickView::SizeRootObjectToView);
viewer.show();
return app.exec();
}
[Output through qDebug()]
("/home/snjee/workspace_qt/maxelecPrjs/build-maxCoffeeTdsMeterApp-Desktop_Qt_5_15_2_GCC_64bit-Debug", "qrc:/qt-project.org/imports", "/opt/Qt/5.15.2/gcc_64/qml")
You can find the answer in the built-in "QML Axes" example source.

Using QtCreator 5.3 for Qt Quick UI project, how to link QML button resource to C++ function call

This is my first post on StackOverflow so please excuse any formatting mistakes I might have made.
I'm building a Qt Quick UI project using Qt Quick Controls 1.1 and I have a simple Button in my QML code that I would like to call into my C++ action class. I see a number of examples on this with earlier versions of Qt, but they do not seem to work in 5.3. I chose Qt Quick Controls 1.1 in the project settings. I know this must not be too complicated to do, but I can't seem to find examples using QtCreator 5.3
Here is my main.qml file:
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
ApplicationWindow {
id: parentWnd
visible: true
width: 640
height: 480
Action {
id: actionSend
onTriggered: console.log("SEND")
}
Button {
id: send
text: "Send Request"
action: actionSend
signal sendSignal()
}
}
Here is my main.cpp:
#include <QApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
Here is the action class where I would like the QML button to call "doSend":
#include<QDebug>
#include<QObject>
class Action : public QObject
{
Q_OBJECT
public:
Action();
public slots:
void doSend();
};
Finally here is my project file:
TEMPLATE = app
QT += qml quick widgets
SOURCES += main.cpp \
action.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Default rules for deployment.
include(deployment.pri)
HEADERS += \
action.h
When I run this, I see the button and I see the logging of "SEND" to the console so I know the QML Action is setup correctly. Any help on how to make the Action call into my action class would be much appreciated!
There are three issues that you're running into here.
The first is that you haven't registered your Action class with QML in main.cpp:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<Action>("StevesModule", 1, 0, "Action");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
The second is that Action is a QML type in the Qt Quick Controls module. It doesn't know anything about your Action class in C++. If you want to use your Action class instead of Qt Quick Controls' Action type, you must import it in your QML file:
import StevesModule 1.0
The third is that you're not calling the doSend() slot anywhere. You can do this in the onClicked handler of Button:
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
import StevesModule 1.0
ApplicationWindow {
id: parentWnd
visible: true
width: 640
height: 480
Action {
id: actionSend
}
Button {
id: send
text: "Send Request"
onClicked: actionSend.doSend()
}
}

Resources