Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

qt - How to trigger a .sh file or a bash command on a Qt4 button click?

Right now, all I have is my QML file, with the button.

 /*PlasmaComponents.*/ToolButton {
    id: shutdownButton
    text: i18n("Shutdown")
    iconSource: "system-shutdown"
    enabled: power.canShutdown
    onClicked: doTheThing();
}

From reading about QML, it seems I'll need to add a C++ process. Is this possible with QML4? If not, could QProcess work? What files would need changing if so?

question from:https://stackoverflow.com/questions/65853041/how-to-trigger-a-sh-file-or-a-bash-command-on-a-qt4-button-click

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can write a process executor class like this :

#include <QProcess>
#include <QVariant>

class Process : public QProcess {
Q_OBJECT

public:
Process(QObject *parent = 0) : QProcess(parent) { }

Q_INVOKABLE void start(const QString &program, const QVariantList &arguments)                {
    QStringList args;

    // convert QVariantList from QML to QStringList for QProcess 

    for (int i = 0; i < arguments.length(); i++)
        args << arguments[i].toString();

    QProcess::start(program, args);
}

Q_INVOKABLE QByteArray readAll() {
    return QProcess::readAll();
}
};

and register them :

#include <QtQml>
#include "process.h"

qmlRegisterType<Process>("Process", 1, 0, "Process");

and finally run your command from QML :

import QtQuick 2.4
import QtQuick.Controls 1.3
import Process 1.0

ApplicationWindow {
width: 800
height: 480
visible: true

Text {
    id: text
}

Process {
    id: process
    onReadyRead: text.text = readAll();
}

Timer {
    interval: 1000
    repeat: true
    triggeredOnStart: true
    running: true
    onTriggered: process.start("poweroff", [ "-f" ]);
 }

-f make forced to power off immediately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...