调整QT中从QWindow继承的另一个类中的事件大小



我正在编写一个简单的程序(C++QTQML),我想在其中实现resizeEvent,然后使用某种模式调整窗口的高度和宽度。我的问题是,当我调整窗口大小时,不会调用resizeEvent。我认为我做错了什么,但我不确定是什么。任何想法都会受到赞赏。

main.cpp

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    QObject *root = engine.rootObjects().first();
    class CMaze maze(root,&engine);
    return app.exec();
}

CMaze.h

class CMaze: public QWindow
{
public:
    CMaze(QObject *root, QQmlApplicationEngine *engine);
private:
    QObject *root;
    QQmlApplicationEngine *engine;
    /*+ Some other variables*/
    void resizeEvent(QResizeEvent *event);
};

CMaze.cpp

CMaze::CMaze(QObject *root,QQmlApplicationEngine *engine)
{
    this->root = root;
    this->engine = engine;
    /* + Some other functionality*/
}
void CMaze::resizeEvent(QResizeEvent *event)
{
    qDebug() << "resize event entered"; // NEVER WRITTEN to CONSOLE WHEN RESIZING 
}

编辑:

main.qml:

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("The Maze")
    Rectangle{
        id: background
        objectName: "background"
        anchors.fill: parent
        color: "#ffffcc"
    }
}

您声明了两个窗口:C++代码中的QWindow(您称之为"错误"的窗口),它与QML完全无关,QML中的ApplicationWindow没有调整大小处理程序。你应该合并这两个窗口。我建议您基于类QQuickView进行以下重构,QQuickView是一个带有集成QML引擎的窗口:

CMaze.h:

class CMaze: public QQuickView
{
public:
    /* QQuickView already has a QML engine and a root object */
    CMaze(/*QObject *root, QQmlApplicationEngine *engine*/);
private:
    // QObject *root;
    // QQmlApplicationEngine *engine;
    /*+ Some other variables*/
protected: /* respect inherited scope */
    /* use override to prevent misdeclaration*/
    void resizeEvent(QResizeEvent *event) override;

};

CMaze.cpp:

CMaze::CMaze(/*QObject *root,QQmlApplicationEngine *engine*/)
{
    //this->root = root; /* replaced by this->rootObject() */
    //this->engine = engine; /* replaced by this->engine() */
    /* + Some other functionality*/
}
void CMaze::resizeEvent(QResizeEvent *event)
{
    qDebug() << "resize event entered";
}

main.cpp:

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    // QQmlApplicationEngine engine;
    // engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    // QObject *root = engine.rootObjects().first();
    CMaze maze; //(root,&engine);
    /* set QML source on maze */
    maze.setSource(QUrl(QLatin1String("qrc:/main.qml")));
    /* show the view */
    maze.show();
    return app.exec();
}

main.qml:

// you already have the window: just keep the rectangle
Rectangle{
    id: background
    objectName: "background"
    anchors.fill: parent
    color: "#ffffcc"
}

相关内容

  • 没有找到相关文章

最新更新