Pelo que entendi, você só pode importar objetos, não funções nuas, para o QML a partir do C ++. Portanto, você precisa transformar sua função open_terminal
em um método de terminal_launcher
, adicionar um objeto terminal_launcher
ao seu arquivo QML e chamar seu método open_terminal
no local apropriado.
Uma adaptação do seu código segue. Observe que renomei terminal_launcher
para TerminalLauncher
para corresponder ao estilo Qt.
terminal_launcher.h
#ifndef TERMINAL_LAUNCHER_H
#define TERMINAL_LAUNCHER_H
#include <QObject>
#include <QProcess>
class TerminalLauncher : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE void open_terminal();
private:
QProcess proc;
};
#endif // TERMINAL_LAUNCHER_H
open_terminal
agora é um método. Ele é marcado como Q_INVOKABLE
para que possa ser usado a partir do QML. proc
foi transformada em uma propriedade de instância para evitar que ela seja coletada como lixo quando o método termina de ser executado, mas o processo filho ainda está por aí.
terminal_launcher.cpp
#include "terminal_launcher.h"
void TerminalLauncher::open_terminal() {
this->proc.start("gnome-terminal", QIODevice::ReadWrite);
}
main.cpp
#include <QGuiApplication>
#include <QQuickView>
#include <QString>
#include <QtQml>
#include "terminal_launcher.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<TerminalLauncher>("com.example.launcher", 1, 0, "Launcher");
QQuickView view;
view.setSource(QUrl("main.qml"));
view.setResizeMode(QQuickView::SizeRootObjectToView);
view.show();
return app.exec();
}
A chamada de qmlRegisterType
é crítica, pois permite que a classe TerminalLauncher seja instanciada no QML. O primeiro argumento é o nome do módulo que deve ser importado. O segundo e o terceiro são os números das versões principais e secundárias. O quarto argumento é o nome pelo qual esta classe é conhecida no QML. Você provavelmente quer torná-lo o mesmo que é em C ++, para evitar ficar louco, mas eu fiz diferente apenas para mostrar que pode ser.
main.qml
import QtQuick 2.0
import QtQuick.Controls 1.1
import com.example.launcher 1.0
Rectangle {
width: 200
height: 51
Launcher {
id: launcher
}
Button {
x: 25
y: 8
width: 150
height: 35
text: "test"
onClicked: launcher.open_terminal();
}
}
Simplifiquei bastante isso para mostrar as partes relevantes. Observe que eu instancio um objeto Launcher
e, em seguida, chamo seu método open_terminal
quando o botão é clicado.
termlaunch.pro
CONFIG += qt
QT += quick
HEADERS = terminal_launcher.h
SOURCES = main.cpp terminal_launcher.cpp
TARGET = termlaunch
Este arquivo de projeto instrui o qmake a criar um binário chamado termlaunch
. Todos esses arquivos devem ir no mesmo diretório.