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

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");
}

Related

How to do QObject::connect to QJSValue?

If Qml can do
MyComponent.connect(someJsFunction);
how can I do this on c++ ???
I need connect JSValue if it isCallable without workarounds. I want to know how it makes qml engine...
QObject::connect(QObject, signal, QJSValue, evaluateFunctionSlot);
This will work. I got the solution from this SO post. That said, I don't know if it aligns with the Qt way of doing it. Their example of invoking a QML method uses QMetaObject::invokeMethod().
main.cpp
#include <QGuiApplication>
#include <QQuickItem>
#include <QQuickView>
class MyClass : public QObject
{
Q_OBJECT
signals:
void cppSignal(const QString &msg);
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view(QUrl(u"qrc:/75069400/main.qml"_qs));
view.show();
QObject *item = view.rootObject();
MyClass myClass;
QObject::connect(&myClass, SIGNAL(cppSignal(QString)),
item, SLOT(callFromCpp(QString)));
emit myClass.cppSignal("this is a test");
return app.exec();
}
#include "main.moc"
main.qml
import QtQuick
Rectangle {
width: 320
height: 240
function callFromCpp(value : string) {
console.log("QML" , value)
}
}
As result the best workaround:
qml
function connect(name, fn){
myObject[name].connect(fn[name]);
}
c++
QMetaObject::invokeMethod(MyObject, "connect", Q_ARG(QVariant, "anySlotName"), Q_ARG(QVariant, QVariant::fromValue(data)));

SetProperty for loaded QML component without using SetContextProperty

I have a C++ plugin system, where a QQmlComponent is created and a qml file is loaded when the user requests a new plugin instance.
Currently I am using setContextProperty() to tell QML about a QObject that is needed for proper initialization.
mEngine->rootContext()->setContextProperty("controller", QVariant::fromValue(mController));
mComponent = new QQmlComponent(mEngine);
mComponent->loadUrl(QUrl{ "qrc:///MyPlugin.qml" });
The problem is, when instantiating a second plugin, both will use the controller of the second one because "controller" is global in QML.
Repeater {
model: controller.numEntries
Is there a way to set a context property locally (only for the current instance)?
I found solutions using setProperty() or QQmlIncubator and setInitialState(), but they all seem to require an object that was already created from my component. But in my plugin I only define the component, which is loaded in the main application through a Loader item. So, when trying these approaches, I always ended up in setting the value in a copy of the item, but not the one being created in my backend.
How can I get access to a property of the component that is created in QML?
mComponent->findChild<QQuickItem*>("controller");
does not give me any results, even if I defined the property in MyPlugin.qml.
Maybe you can create a QObject based class and have a slot and instead of using property you can call slot to slot create a new property in c++ and return it to QML
ControllerCreator.h
#ifndef CONTROLLERCREATOR_H
#define CONTROLLERCREATOR_H
#include <QObject>
class ControllerCreator : public QObject {
Q_OBJECT
public:
explicit ControllerCreator(QObject *parent = nullptr);
signals:
public slots:
int propertyCreator();
private:
int m_example;
};
#endif // CONTROLLERCREATOR_H
ControllerCreator.cpp
#include "ControllerCreator.h"
ControllerCreator::ControllerCreator(QObject *parent)
: QObject(parent), m_example(0)
{
}
int ControllerCreator::propertyCreator()
{
m_example++;
return m_example;
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "ControllerCreator.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
ControllerCreator controllerCreator;
engine.rootContext()->setContextProperty("creator", &controllerCreator);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Column{
anchors.fill: parent
Text{
text: creator.propertyCreator()
color: "blue"
}
Text{
text: creator.propertyCreator()
color: "red"
}
Text{
text: creator.propertyCreator()
color: "green"
}
}
}

Qml QTouchDevice

I am new in Qt. I am working on windows desktop application and using Qt with qml. On PC that hasn't QTouchDevices, splitter between component (element that allow you resize component on window) works good with mouse (screenshot "Good distance"), but if screen is touchscreen I have next problem, please look on screenshot "Wrong distance".
My application shouldn't support any touch device. So how to disable this Qt feature? I need the same behavior like on device without touch screen.
Wrong distance
Good distance
I have tried disable touch device using privet methods using next sample:
QWindowSystemInterface::unregisterTouchDevice(QTouchDevice::devices().first());
This works, but QWindowSystemInterface is private class and it disable touchscreen. And one more in QTCreator splitters work fine, exactly as I need.
If you can't patch Qt, the only way that I can think of would be to iterate through the children, searching for the MouseArea. For example, suppose you had this QML:
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1
ApplicationWindow {
width: 600
height: 400
visible: true
property alias splitView: splitView
SplitView {
id: splitView
anchors.fill: parent
Rectangle {
width: 200
Layout.maximumWidth: 400
color: "lightblue"
Text {
text: "View 1"
anchors.centerIn: parent
}
}
Rectangle {
id: centerItem
Layout.minimumWidth: 50
Layout.fillWidth: true
color: "lightgray"
Text {
text: "View 2"
anchors.centerIn: parent
}
}
}
}
You could then print out the object tree of the SplitView like so:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QDebug>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject *window = engine.rootObjects().first();
QQuickItem *splitView = window->property("splitView").value<QQuickItem*>();
splitView->dumpObjectTree();
return app.exec();
}
That gives you:
SplitView_QMLTYPE_1::
QQmlComponent::
QQuickSystemPalette::
QObject_QML_2::
QQmlComponent::
QQuickItem::
QQuickItem::
QQuickItem::
QQuickLoader_QML_3::
QObject_QML_4::
QQuickMouseArea_QML_5::
QQuickRectangle::
QQmlContext::
QQuickItem::
QQmlComponentAttached::
QQuickRectangle::
QQuickText::
QQuickLayoutAttached::
QQuickRectangle::
QQuickText::
QQuickLayoutAttached::
QQuickLayoutAttached::
QObject::dumpObjectTree() prints out metaObject->className(), so we know to look for an object whose metaObject has a className matching that:
Then:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QScreen>
#include <QWindow>
#include <QDebug>
QQuickItem *findMouseArea(QQuickItem *item)
{
foreach (QQuickItem *childItem, item->childItems()) {
if (QString(childItem->metaObject()->className()).startsWith(QStringLiteral("QQuickMouseArea_QML"))) {
return childItem;
} else {
QQuickItem *mouseArea = findMouseArea(childItem);
if (mouseArea) {
return mouseArea;
}
}
}
return 0;
}
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QWindow *window = qobject_cast<QWindow*>(engine.rootObjects().first());
QQuickItem *splitView = window->property("splitView").value<QQuickItem*>();
QQuickItem *mouseArea = findMouseArea(splitView);
mouseArea->setProperty("defaultMargin", QVariant(window->screen()->physicalDotsPerInch() / 25.4));
return app.exec();
}
Apparently, Screen::pixelDensity is calculated using the physical dots per inch of the screen, divided by 25.4, so we copy that as well. You could use any other value there.
You will need to adapt the code should a second MouseArea ever be introduced, for example.
It's still largely dependent on private API, but it doesn't touch Qt code, at least.
Quick&Easy: enable/disable mouse and touch synthesizing
No need to patch things or doing any crazy tree lookups, just enable or disable mouse or touch synthesizing.
Qt::AA_SynthesizeTouchForUnhandledMouseEvents
Qt::AA_SynthesizeMouseForUnhandledTouchEvents
Just disable what you don't want, either mouse or touch to accept only authentic events.

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();
}

passing signal with parameters from qml to c++

I dont know how to pass parameters from QML file to c++ file in Qt.
QML code:
import QtQuick 1.1
Rectangle{
id:loin
height: 272
width:480
property alias loguid:loginuid
signal sigHome()
Rectangle{
id:rect1
width:parent.width-80
height:24
TextInput {
id:loginuid
maximumLength: 16
width: maximumLength * 20
focus: false
validator: RegExpValidator { regExp: /\d+/ }
KeyNavigation.down: login1
}
}
Button{
id: login1
x: 195
y: 187
height:30;
focus:false
border.color:"black"
opacity: activeFocus ? 1.0 : 0.5
Text{
text:"LOGIN"
anchors.horizontalCenter:login1.horizontalCenter;
anchors.verticalCenter:login1.verticalCenter;
}
Keys.onReturnPressed: {
if(loginuid.text < 1000000000000000)
{
text1.opacity=0.1
error1.visible=true
errorText.text="\n enter valid 16 digit number\n"
errorOk.focus=true
loginuid.focus=false
}
else{
loginuid.focus=false
loin.sigHome()
}
}
}
}
c++ code:
#include <QApplication>
#include <QDeclarativeView>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
int uid;
QDeclarativeView view;
view.setSource(QUrl::fromLocalFile("main.qml"));
view.show();
return app.exec();
}
When I press the login button rect1.text content shud go to main.cpp file and uid in the main.cpp get dat value. Something like this uid=rect1.text.
How to do it?
I wouldn't try to listen for a QML signal from the C++ side. Calling a C++ method with arguments is much easier and achieves the same:
To do so you have to:
define a slot or invokable method accepting the required arguments
register the class carrying the method with the declarative engine
then you can set an instance of this class as a property of your root context and finally call this method from QML
This topic is also well covered in the official documentation.
Thanks, sebasgo, your response helped me. I used signals and slots to communicate.
I created a signal in main.qml.
signal info(string msg)
and in login page
else{
info(loginUid.text)
loginuid.focus=false
loin.sigHome()
}
and in main.cpp I connected it to d slot
main.cpp goes like this
#include <QtGui>
#include <QApplication>
#include <QDeclarativeView>
#include <QtDeclarative>
class DeclarativeView : public QDeclarativeView
{
Q_OBJECT
public:
DeclarativeView(const QUrl & source) : QDeclarativeView(source)
{
}
public slots:
void readText(QString quid)
{
qdebug<<quid;
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
QString file = "main.qml";
QApplication app(argc, argv);
DeclarativeView view(QUrl::fromLocalFile(file));
QDeclarativeItem *item = qobject_cast<QDeclarativeItem *>(view.rootObject());
QObject::connect(item, SIGNAL(info(QString)), &view, SLOT(readText(QString)));
view.show();
return app.exec();
}
Create a GUI controller C++ class:
class UiController : public QObject
{
Q_OBJECT
public:
UiController();
virtual ~UiController();
public slots:
void cal_daysoff__onDoubleClicked(const QDate& date);
};
In QML file you define, say, a calendar control in which you connect a signal to a slot in the controller:
Calendar{
id: cal_daysoff
Layout.fillWidth: true
Layout.fillHeight: true
onDoubleClicked: UiController.cal_daysoff__onDoubleClicked(date)
}
In main file, when launching the QML interface, connect the interface to the controller:
#include "uicontroller.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
UiController control;
engine.rootContext()->setContextProperty("UiController", &control);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}

Resources