我正在编写一个简单的程序( C ++ , QT , QML ),我想在其中实现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"
}
}
答案 0 :(得分:2)
你要声明2个窗口:C ++代码中的QWindow(你称之为“错误”窗口的那个)与你的QML完全无关,而你的QML中的ApplicationWindow没有调整大小处理程序。你应该合并这两个窗口。我建议你进行以下重构,基于类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"
}