QtQuick2无法将ApplicationWindow关闭信号连接到方法(C++新手) [英] QtQuick2 Can't connect ApplicationWindow closing signal to method (C++ novice)

查看:35
本文介绍了QtQuick2无法将ApplicationWindow关闭信号连接到方法(C++新手)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为我用 QtQuick 编写的应用程序绑定关闭时"事件时遇到问题.我想做的是执行标准的确认退出"方法,也许我会以错误的方式解决这个问题.

I'm having trouble binding an "On Close" event for my application written in QtQuick. What I'd like to do is do the standard "confirm exit" method and maybe I'm going about this the wrong way.

据我所知,我想要类似的东西

As I understand it I want something like

void MainDriver::onClose(QEvent* event)
{
    if(notSaved)
    {
      //prompt save
      event->ignore();
    }
    else
      event->accept();
}

但是似乎 QQuickCloseEvent 不是从 QEvent 派生的,或者我包含了错误的标头(很有可能),而且我找不到它的定义位置,以便我可以连接信号.

however it seems QQuickCloseEvent isn't derived from QEvent or I'm including the wrong header (very possible) and I can't find out where it is defined so that I can connect the signals.

有没有更好的方法来解决这个问题?现在我像这样实例化主窗口:

Is there a better way to get around this? Right now I instantiate the main window like this:

QQmlApplicationEngine engine; //Actually initialized in the constructor
engine.load(QUrl("qrc:/qml/Window.qml"));
QObject *topLevel = engine.rootObjects().value(0);
QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);

我使用 ApplicationWindow (QtQuick Controls) 作为从 QWindow 派生的主窗口.我对这里的建议持开放态度,我想坚持使用 QtQuick,而不是将所有内容都包装在标准 QWindow 或 QMainWindow 中,但这也许是一条糟糕的路线.任何帮助将不胜感激.

I'm using ApplicationWindow (QtQuick Controls) as the main window which is derived from QWindow. I'm open to suggestion here, I'd like to stick to QtQuick and not wrap everything in a standard QWindow or QMainWindow, but maybe that's a poor route to take. Any help would be appreciated.

推荐答案

您可以使用 EventFilter 处理主窗口控制器中的关闭事件:

You can use EventFilter to handle close event in main window's controller:

class MyEventFilter : public QObject
 {
     Q_OBJECT

 protected:
     bool eventFilter(QObject *obj, QEvent *event);
 };

 bool MyEventFilter::eventFilter(QObject *obj, QEvent *event)
 {
     if (event->type() == QEvent::Close) 
     {
         // TODO: confirm
         return true;
     } else 
     {
         // standard event processing
         return QObject::eventFilter(obj, event);
     }
 }

在你的 main() 中:

And in your main():

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    MyEventFilter filter;
    QtQuick2ApplicationViewer viewer;

    viewer.installEventFilter(&filter);
    viewer.setMainQmlFile(QStringLiteral("qml/QCloseConfirm/main.qml"));

    viewer.showExpanded();

    return app.exec();
}

这里是示例.但它似乎并不完美.应该有更好的解决方案.

Here is example. But it doesn't seem to be perfect. There should be a better solution.

这篇关于QtQuick2无法将ApplicationWindow关闭信号连接到方法(C++新手)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆