qml Camera save same image with different resolutions - qt

I'm using QML's Camera component and Camera.imageCapture to save images.
I want to save multiple resolutions of the same image when user click "Capture" button.
The code I'm trying to run is simply like this:
// 160x120
camera.imageCapture.resolution = Qt.size(160,120)
camera.imageCapture.captureToLocation("/location/")
// 320x340
camera.imageCapture.resolution = Qt.size(320,240)
camera.imageCapture.captureToLocation("/anotherLocation/")
camera.imageCapture.resolution = Qt.size(-1,-1) // set to default again
Thanks.

If you'd save your camera input to a QImage you can save and resize and save again using QImage's image.save() and image.scaled() functions.
I've used these functions before for resizing images and it works perfect.
However I don't know how you can save the camera input to a QImage, but I'll look into that and report back.
I know it's not a full answer to your question, but it's a start. I hope that this was helpful.

Here is how I have solved:
Save the image with highest resolution available in Camera:
Component.onCompleted: {
camera.imageCapture.resolution = camera.imageCapture.supportedResolutions[camera.imageCapture.supportedResolutions.length-1]
}
Give the path of that file to the QImage's constructor.
Then scale & save:
Full Code:
imageresizer.cpp:
#include "imageresizer.h"
#include <QImage>
ImageResizer::ImageResizer(QObject *parent) : QObject(parent)
{}
void ImageResizer::resizeImage(int width, int height, QString file, QString savefile)
{
QImage img(file);
img = img.scaled(width, height);
img.save(savefile);
}
imageresizer.h:
#ifndef IMAGERESIZER_H
#define IMAGERESIZER_H
#include <QObject>
class ImageResizer : public QObject
{
Q_OBJECT
public:
explicit ImageResizer(QObject *parent = nullptr);
signals:
public slots:
void resizeImage(int width, int height, QString file, QString savefile);
};
#endif // IMAGERESIZER_H
Don't forget to make it available from QML:
int main(int argc, char *argv[])
{
qmlRegisterType<ImageResizer>("project.imageresizer", 1, 0, "ImageResizer"); // Here
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml:
import project.imageresizer 1.0
Window {
id: mainWindow
visible: true
width: 1024
height: 600
title: ""
ImageResizer {
id: imageResizer
}
// Use it like:
// imageResizer.resizeImage(100,100,imgPath,scaleImgPath)
}

Related

How to display QML view( with scroll) to load and display multiline Text around 10 million lines from file [duplicate]

I have a Qt application and I'd like to show some log. I use a TextArea. However, if the log is large or the events come too fast the GUI can't draw Textarea fast enough.
I have analyzed this problem with Qt Creator (QML Profiler) and if the log is large it takes 300 ms to draw the GUI. I use this software on a Raspberry Pi2.
Any ideas how to solve this? Should I use other QML controls? Thanks.
QML code:
TextArea {
text: appHandler.rawCommunication
readOnly: true
}
C++ code:
Q_PROPERTY(QString rawCommunication READ rawCommunication WRITE setrawCommunication NOTIFY rawCommunicationChanged)
void setrawCommunication(QString val)
{
val.append("\n");
val.append(m_rawCommunication);
m_rawCommunication = val;
emit rawCommunicationChanged(m_rawCommunication);
}
Use a view, like ListView. They instantiate their delegates as needed, based on which data the view says it needs to show depending on the position the user is at in the list. This means that they perform much better for visualising large amounts of data than items like TextArea, which in your case is going to keep a massive, ever-growing string in memory.
Your delegate could then be a TextArea, so you'd have one editable block of text per log line. However, if you don't need styling, I'd recommend going with something a bit lighter, like TextEdit. Taking it one step further: if you don't need editable text, use plain old Text. Switching to these might not make much of a difference, but if you're still seeing slowness (and have lots of delegates visible at a time), it's worth a try.
I tried the ListView suggestion but it has several drawbacks:
No easy way to keep the view positioned at the bottom when new output is added
No selection across lines/delegates
So I ended up using a cached TextArea, updating once every second:
TextArea {
id: outputArea_text
wrapMode: TextArea.Wrap
readOnly: true
font.family: "Ubuntu Mono, times"
function appendText(text){
logCache += text + "\n";
update_timer.start();
}
property string logCache: ""
Timer {
id: update_timer
// Update every second
interval: 1000
running: false
repeat: false
onTriggered: {
outputArea_text.append(outputArea_text.logCache);
outputArea_text.logCache = "";
}
}
Component.onCompleted: {
my_signal.connect(outputArea_text.appendText)
}
}
try this approach:
create a c++ logger class
append all logs to this class
and print them using some action, example a button click
this will solve your performance issue
Example of code:
Logger.h
#ifndef LOGGER_H
#define LOGGER_H
#include <QQmlContext>
#include <QObject>
#include <QStringList>
#include <QQmlEngine>
#include <QString>
#include <QtCore>
#include <QDebug>
class Logger : public QObject
{
Q_OBJECT
public:
explicit Logger(QObject *parent = 0);
~Logger();
Q_INVOKABLE QStringList *getLogStream();
Q_INVOKABLE void printLogStream();
Q_INVOKABLE void appendLog(QString log);
Q_INVOKABLE void log(QString log="");
Q_INVOKABLE void log(QString fileName, QString log);
signals:
public slots:
private:
QStringList* stringStream_;
};
#endif // LOGGER_H
Logger.cpp
#include "logger.h"
Logger::Logger(QObject *parent) :
QObject(parent),
stringStream_(new QStringList)
{
}
~Logger(){
if(stringStream_ != NULL)
{
delete stringStream_;
stringStream_ = NULL;
}
}
QStringList* Logger::getLogStream(){
return stringStream_;
}
void Logger::printLogStream()
{
QStringListIterator itr(*stringStream_);
while (itr.hasNext())
qDebug()<< itr.next()<<"\n";
}
void Logger::appendLog(QString log){
stringStream_->push_back(log) ;
}
void Logger::log(QString fileName,QString log)
{
#ifdef ENABLElogs
fileName.push_front(" [");
if(!fileName.contains(".qml"))
{
fileName.append(".qml]:");
}
qDebug()<<fileName<<log;
#else
Q_UNUSED(log);
Q_UNUSED(fileName);
#endif
}
void Logger::log(QString log)
{
#ifdef ENABLElogs
qDebug()<<log;
#else
Q_UNUSED(log);
#endif
}
main.cpp
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include "logger.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer *viewer = new QtQuick2ApplicationViewer;
Logger* stream = new Logger;
viewer->rootContext()->setContextProperty("Stream",stream);
viewer->setMainQmlFile(QStringLiteral("qml/project/main.qml"));
viewer->showExpanded();
return app.exec();
}
main.qml
import QtQuick 2.0
import QtQuick.Controls 1.1
Rectangle {
width: 800
height: 480
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
Component.onCompleted: Stream.appendLog("Text object is completed")
}
Column{
x:300
Button{
text:"append"
onClicked: {
Stream.appendLog("MouseArea object clicked")
}
Component.onCompleted: Stream.appendLog("Button object is completed")
}
Button{
text:"logger"
onClicked: {
Stream.printLogStream()
}
Component.onCompleted: Stream.appendLog("Button logger object is completed")
}
}
TextArea{
text:"blablabla"
Component.onCompleted: Stream.appendLog("TextArea object is completed")
}
Component.onCompleted: Stream.appendLog("the main object is completed")
}
project.pro
#add this line
# comment it, run qmake and recompile to disable logs
DEFINES += ENABLElogs
using this approch you can stop all logs with a single line change when you want to release your soft
However, I have included complete code, using "QAbstractListModel" for a Logging heavy data to QML
listmodel.h
#ifndef LISTMODEL_H
#define LISTMODEL_H
#include <QAbstractListModel>
class ListModel: public QAbstractListModel
{
Q_OBJECT
public:
ListModel();
// Q_PROPERTY(QStringList logs READ name WRITE nameChanged)
int rowCount(const QModelIndex & parent = QModelIndex()) const;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
Q_INVOKABLE QVariant activate(int i);
private:
QStringList m_list;
};
#endif // LISTMODEL_H
listmodel.cpp
#include "listmodel.h"
#include <QFile>
#include <QHash>
ListModel::ListModel()
{
QFile file("/home/ashif/LogFile");
if(!file.open(QIODevice::ReadOnly))
{
qDebug( "Log file open failed" );
}
bool isContinue = true;
do
{
if(file.atEnd())
{
isContinue = false;
}
m_list.append(file.readLine());
}
while( isContinue);
}
int ListModel::rowCount(const QModelIndex & parent ) const
{
return m_list.count();
}
QVariant ListModel::data(const QModelIndex & index, int role ) const
{
if(!index.isValid()) {
return QVariant("temp");
}
return m_list.value(index.row());
}
QVariant ListModel::activate(int i)
{
return m_list[i];
}
main.qml
import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
visible: true
ListView
{
width: 200; height: 250
anchors.centerIn: parent
model:mylistModel
delegate: Text
{
text:mylistModel.activate(index)
}
}
}
main.cpp
#include <QGuiApplication>
#include <QQmlContext>
#include <QQmlApplicationEngine>
#include "logger.h"
#include "listmodel.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Logger myLogger;
ListModel listModel;
engine.rootContext()->setContextProperty("mylistModel", &listModel);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}

Prevent QApplication app from closing if a service is running

I have a QML app in which I have subclassed QApplication to create my main screen with QML. The issue i have is on clicking Close button the application closes as intended, but I want to handle a situation where if some services are running I want to override close button behaviour.
I tried overriding closeEvent() without any luck. Can anyone point me to some ways I can handle this?
UPDATE : This is the code snippet I tried
class SingleApplication : public QApplication {
Q_OBJECT
public:
SingleApplication(int &argc, char **argv);
void closeEvent ( QCloseEvent * event )
{
event->ignore();
}
}
MAIN.cpp
#include "view.h"
#include <QDebug>
#include <QDesktopWidget>
#include "SingleApplication.h"
int main(int argc, char *argv[])
{
SingleApplication app(argc, argv);
if(!app.isRunning()) {
app.processEvents();
View view(QUrl("qrc:/qml/main.qml"));
#ifdef Q_OS_LINUX
view.setFlags(Qt::WindowMinimizeButtonHint|Qt::WindowCloseButtonHint);
#endif
view.setMaximumSize(QSize(1280,700));
view.setMinimumSize(QSize(1280,700));
// Centering the App to the middle of the screen
int width = view.frameGeometry().width();
int height = view.frameGeometry().height();
QDesktopWidget wid;
int screenWidth = wid.screen()->width();
int screenHeight = wid.screen()->height();
view.setGeometry((screenWidth/2)-(width/2),(screenHeight/2)-(height/2),width,height);
view.show();
return app.exec();
}
return 0;
}
There is no QApplication::closeEvent. Such virtual function belongs to QWidget.
Use of QApplication indicated that you have normal QWidget container for your QML UI (as you say UI is based on QML though). You should rather override that widget closeEvent e.g.:
class MyMainWidget : public QWidget // or is it QMainWindow?
{
// snip
private:
void closeEvent(QCloseEvent*);
}
void MyMainWidget::closeEvent(QCloseEvent* event)
{
// decide whether or not the event accepted
if (condition())
event->accept();
}
And if your container widget is not overridden yet (simply QWidget?), well, now you have to do so.
And you did not say whether or not you want to keep app window running. I assume you want that as well.

QQuickWidget grab image

I am saving an image of a QQuickWidget with several QML children but all I have is a blank image.
C++ side:
QQuickWidget* content..
content->setSource(QUrl("qml:/main.qml"));
QPixmap *pm = content->grab(QRect(QPoint(0,0),QSize(-1,-1));
pm->save("someFilename.png", 0, 100);
QML side:
Rectangle{ width: 5; height: 5; color: "yellow"; objectname: "rootobj"}
In the QML I wish to dynamically add children and be able to show them in the image. I have tried QQuickWindow grabWindow method with a connection to a slot and it works but it captures only the window visible area and I need to capture the whole QML.
I believe this is not rocket science just that I am not getting it somewhere. Thanks for your replies!
Addendum:
Ok, I do not think its the issue of before/after rendering since I can see all the qml children before I call the picture grabber. So sorry for not being precise.
c++ side:
QQuickWidget* content..
content->setSource(QUrl("qml:/main.qml"));
//do all my dynamic qml children adding
After I can visually see all my qml:
QPixmap *pm = content->grab(QRect(QPoint(0,0),QSize(-1,-1));
pm->save(....
Unless I am wrong, I dont think its rendering issue. Thank you!
Issue is like Mido said. You can solve it like follows.
Create a class Viewer:
viewer.h
class Viewer : public QQuickView{
Q_OBJECT
public:
explicit Viewer(QWindow *parent = 0);
Viewer(bool showBar);
virtual ~Viewer();
void setMainQmlFile(const QString file);
void addImportPath(const QString path);
public slots:
void beforeRendering();
void afterRendering()
}
Viewer.cpp
#include "viewer.h"
Viewer::Viewer(QWindow *parent)
: QQuickView(parent)
{
setWidth(800);
setHeight(480);
connect(this, SIGNAL(beforeRendering()), this, SLOT(beforeRendering()));
connect(this, SIGNAL(afterRendering()), this, SLOT(afterRendering()));
}
void Viewer::setMainQmlFile(const QString file)
{
setSource(QUrl::fromLocalFile(file));
}
void Viewer::addImportPath(const QString path)
{
engine()->addImportPath(path);
}
void Viewer::beforeRendering()
{
//
}
void Viewer::afterRendering()
{
//grab window
QImage img = this->grabWindow();
img.save(path);
//or your code
}
main.cpp
Viewer *viewer = new Viewer;
//
///
//
viewer->setMainQmlFile(QStringLiteral("qml/main.qml"));
viewer->show();
I think your issue is that the capture screen is done before the rendering of the QML object.
In order to make it work you should connect the grab of the signal after rendering signal:
connect(this, SIGNAL(beforeRendering()), this, SLOT(sltBeforeRendering()));
connect(this, SIGNAL(afterRendering()), this, SLOT(sltAfterRendering()));
do the grab in sltAfterRendering slot.
To grab screen I use the grabWindow() function and I call it from QML.
It depends on the behaviour that you want from your software.
Try this:
grabber.h
#ifndef GRABBER_H
#define GRABBER_H
#include <QObject>
#include <QImage>
#include <QQuickView>
class Grabber : public QObject
{
Q_OBJECT
public:
explicit Grabber(QObject *parent = 0);
Grabber(QQuickView *view);
~Grabber();
Q_INVOKABLE void capture(QString const &path) const;
signals:
public slots:
private:
QQuickView* view_;
};
#endif // GRABBER_H
grabber.cpp
#include "grabber.h"
Grabber::Grabber(QObject *parent) :
QObject(parent)
{
}
Grabber::Grabber(QQuickView* view) :
view_(view)
{
}
Grabber::~Grabber()
{
if(view_ != NULL)
{
delete view_;
view_ = NULL;
}
}
void Grabber::capture(QString const &path) const
{
QImage img = view_->grabWindow();
img.save(path);
}
main.cpp
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QQmlContext>
#include <QQmlEngine>
#include "grabber.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer *viewer = new QtQuick2ApplicationViewer;
Grabber * grab = new Grabber(viewer);
viewer->setHeight(480);
viewer->setWidth(800);
viewer->rootContext()->setContextProperty("grab", grab);
viewer->setMainQmlFile(QStringLiteral("qml/main.qml"));
viewer->showExpanded();
return app.exec();
}
Call it from QML with:
grab.capture(path + "imageName.png")

How to connect a Qt Quick button click to a c++ method

I've just started to learn about Qt Mobile programming with Qt Quick 2.0 and I've been on google the whole day and its driving me crazy so here goes.
I have got just your standard qt quick mobile app that qt makes for you. Here is all the files.
(I'm brand new to this so these might be noob qu's, sorry)
Ok so here is my list of I Don't Knows:
how on earth do I connect this class method to the button click in the qml file.
Would it be possible to connect the same click and pass params through the click from the qml to the method and if so how would I do it?
and also I was wondering if I could link the class to the qt quick like a regular QWidget class for instance:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
SomeClass *sc = new SomeClass();
QtQuick2ApplicationViewer viewer;
// this I guess would be more like the Widget method but this i really dont know
// about, just a question I'm throwing out there
viewer. (Link qt quick qml to object "sc"(Containing all my processes))
viewer.setMainQmlFile(QStringLiteral("qml/Final2/main.qml"));
viewer.showExpanded();
return app.exec();
}
The main(.)cpp file
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/Final2/main.qml"));
viewer.showExpanded();
return app.exec();
}
This is just the button element from my main.qml
Button {
id: btn
y: 443
height: 39
text: "Click Me"
anchors.bottom: parent.bottom
anchors.bottomMargin: 8
anchors.right: parent.right
anchors.rightMargin: 25
anchors.left: parent.left
anchors.leftMargin: 15
}
This is just some random class header :
#ifndef SOMECLASS_H
#define SOMECLASS_H
#include <QObject>
#include <QDebug>>
class SomeClass : public QObject
{
Q_OBJECT
public:
explicit SomeClass(QObject *parent = 0);
signals:
public slots:
void buttonClicked();
void buttonClicked(QString &in);
};
#endif // SOMECLASS_H
Of course the cpp file :
#include "someclass.h"
SomeClass::SomeClass(QObject *parent) :
QObject(parent)
{
}
void SomeClass::buttonClicked()
{
// do something
}
void SomeClass::buttonClicked(QString &in)
{
qDebug() << "Your string was : " << in;
}
I really appreciate all the help.
Thank you.
First, you need to export the SomeClass object to QtQuick (is that your third question?):
SomeClass sc;
viewer.rootContext()->setContextProperty(QStringLiteral("_someObject"), &sc);
This makes the sc object available in QtQuick, under the name "_someObject".
Then, in the QML use it like this:
Button {
....
onClicked: {
_someObject.buttonClicked(); //_someObject is the name used in setContextProperty.
}
}
This assumes the Button has a signal clicked() that's emitted on click/touch. Not knowing which Button component you use, I can't check that.
To pass an argument, just do
onClicked: {
_someObject.buttonClicked("Something");
}

Capture QML drawing buffer, without displaying

I need to grab each QML (QtQuick 2) drawing frame and sent it over the network.
At the moment I have used method listed below, but this method has two big disadvantage
1) Due to Qt5 documentation grabWindow() function has performance issues
2) It can't work with hidden QML window
Is it possible to get OpenGL render buffer right after QQuickWindow::afterRendering ?
Using FBOs ? Shared opengl context ?
class Grab: public QObject
{
public:
Grab( QQuickWindow * wnd ) : wnd_(wnd) {}
public slots:
void Grabme()
{
QImage image = wnd_->grabWindow();
}
private:
QQuickWindow *wnd_;
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/grab1/main.qml"));
viewer.showExpanded();
Grab grab( &viewer );
QObject::connect( &viewer, &QtQuick2ApplicationViewer::frameSwapped,
&grab, &Grab::Grabme, Qt::DirectConnection );
return app.exec();
}
Example bellow can grab any qml content to FBO and then sent it as Image via signal.
Only one problem of this approach is visibility, grab window must be visible for successful grabbing. If anybody knows how to prevent this you can help me and provide more advanced approach.
// main.cpp
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
GrabWindow grab;
grab.setResizeMode( QQuickView::SizeViewToRootObject );
grab.setSource( QUrl::fromLocalFile("qml/main.qml") );
grab.setFlags( Qt::Popup );
grab.show();
return app.exec();
}
// grabwindow.hpp
#pragma once
#include <QOpenGLFramebufferObject>
#include <QScopedPointer>
#include <QQuickView>
#include <QImage>
class GrabWindow: public QQuickView
{
Q_OBJECT
signals:
void changeImage( const QImage &image );
public:
GrabWindow( QWindow * parent = 0 );
private slots:
void afterRendering();
void beforeRendering();
private:
QScopedPointer<QOpenGLFramebufferObject> fbo_;
};
// grabwindow.cpp
#include "grabwindow.hpp"
#include <limits>
GrabWindow::GrabWindow( QWindow * parent ) :
QQuickView( parent )
{
setClearBeforeRendering( false );
setPosition( std::numeric_limits<unsigned short>::max(), std::numeric_limits<unsigned short>::max() );
connect( this, SIGNAL( afterRendering() ), SLOT( afterRendering() ), Qt::DirectConnection );
connect( this, SIGNAL( beforeRendering() ), SLOT( beforeRendering() ), Qt::DirectConnection );
}
void GrabWindow::afterRendering()
{
if( !fbo_.isNull() )
{
emit changeImage( fbo_->toImage() );
}
}
void GrabWindow::beforeRendering()
{
if (!fbo_)
{
fbo_.reset(new QOpenGLFramebufferObject( size(), QOpenGLFramebufferObject::NoAttachment) );
setRenderTarget(fbo_.data());
}
}
I managed to find a trick to make grabWindow() work when the Window is "not visible". The trick is to set the window's visibility: Window.Minimized and the flags: Qt.Tool. The window is not displayed to the user, but to the Qt's internals it appears to be visible and the grabWindow() method call works as expected. Remember to call that method only once the scene has been initialised.
The only problem with this solution (that I have come across) is that if the window's color property is set to transparent, the captured content has black background.
With later versions of Qt 5.X you can also use the software render backend.
The following renders any scene in the background without any visible window or OpenGL tricks:
// main.cpp
#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QQuickItem>
#include <QQuickWindow>
#include <QQuickRenderControl>
int main(int argc, char *argv[])
{
const char *source = "qrc:/main.qml";
if (argc > 1) source = argv[1];
QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software);
QGuiApplication app{argc, argv};
QQuickRenderControl renderControl;
QQuickWindow window{&renderControl};
QQmlEngine engine;
QQmlComponent component{
&engine,
QUrl{QString::fromUtf8(source)}
};
QQuickItem *rootItem = qobject_cast<QQuickItem *>(component.create());
window.contentItem()->setSize(rootItem->size());
rootItem->setParentItem(window.contentItem());
window.resize(rootItem->size().width(), rootItem->size().height());
QImage image = renderControl.grab();
image.save("output.png");
return 0;
}

Resources