我在将c ++信号连接到QML窗口中时遇到问题,所有事件按钮都可以正常工作,但是当我尝试附加信号时,我从输出控制台收到"参考错误"。
#include <QApplication>
#include <QQuickWidget>
#include <QQmlContext>
#include <QQuickView>
#include "settings.h"
#include "settingswindow.h"
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QQuickView wdg;
MainWindow mywnd;
wdg.engine()->rootContext()->setContextProperty("connection", &mywnd);
wdg.setSource(QUrl("qrc:/qml_vertical_7p/MainWindow.qml"));
wdg.show();
return app.exec();
}
这门课,我也尝试在我的两个信号上加Q_SIGNAL
#include <QObject>
#include <QQuickWidget>
#include <QQmlContext>
#include <QQmlEngine>
#include <QTimer>
#include <QTime>
#include <QDate>
#include <QDebug>
class MainWindow : public QObject
{
Q_OBJECT
private:
QString _windowPrefix;
const QString _mainWindowName = "MainWindow.qml";
QQuickWidget *_window;
QTimer _timer;
public:
explicit MainWindow(QObject *parent = nullptr);
void Show();
Q_INVOKABLE void secreetButtonPressed();
Q_INVOKABLE void secreetButtonReleased();
Q_INVOKABLE void onTimeChanged();
signals:
void timeChanged(QString formatted_time);
void dataChanged(QString formatted_data);
}
import QtQuick 2.4
import QtQuick.Controls 2.0
Item
{
id:wnd
visible: true
width: form.height
height: form.width
Page
{
rotation: 90
MainWindowForm
{
id: form
x: 0
y: -800
mouseArea.onPressed: {
connection.secreetButtonPressed()
}
mouseArea.onReleased: {
connection.secreetButtonReleased()
}
}
Connections
{
target: connection
onTimeChanged:{
}
}
}
}
我希望 c++ 中发出的信号会修改 QML 窗口,但结果是:
QML Connections: Cannot assign to non-existent property "onTimeChanged"
ReferenceError: connection is not defined
你的类 MainWindow 中有名称冲突:
Q_INVOKABLE void onTimeChanged();
signals:
void timeChanged(QString formatted_time);
所以,也许Qt无法理解你想使用什么功能。尝试重命名其中一个
我认为这是你的语法您必须尝试:
Connections{
target: connection
function onTimeChanged() {
//doing stuff
}
}