首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取C++中ApplicationWindow的大小

获取C++中ApplicationWindow的大小
EN

Stack Overflow用户
提问于 2018-07-07 20:24:06
回答 1查看 603关注 0票数 2

如何在C++中获得QML ApplicationWindow的大小?

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

if (engine.rootObjects().isEmpty())
    return -1;

QObject *application_object = engine.rootObjects().first();

// Throws ApplicationWindow_QMLTYPE_11::height(int), no such signal
QObject::connect(application_object, SIGNAL(height(int)), &my_obj_here, SLOT(set_game_height(int)));
QObject::connect(application_object, SIGNAL(width(int)), &my_obj_here, SLOT(set_game_width(int)));

return app.exec();

我意识到我也无法获得ApplicationWindow内容的大小(减去工具栏、菜单栏等),但是我如何访问它呢?

尝试使用property方法访问window_object上的window属性时返回一个空指针。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-08 07:33:06

一种可能的解决方案是使用QQmlProperty获取QQuickItem,然后使用信号heightChangedwidthChanged连接,这些信号只通知属性已更改,但不指示值,因此必须使用方法height()width()

QObject *topLevel = engine.rootObjects().first();
QQuickItem *contentItem =qvariant_cast<QQuickItem *>(QQmlProperty::read(topLevel, "contentItem"));
if(contentItem){
    QObject::connect(contentItem, &QQuickItem::heightChanged,
                     [&my_obj_here, contentItem](){
        my_obj_here.set_game_height(contentItem->height());
    });
    QObject::connect(contentItem, &QQuickItem::widthChanged, 
                     [&my_obj_here, contentItem](){
        my_obj_here.set_game_width(contentItem->width());
    });
}

另一种解决方案是在QML端建立连接,为此您必须创建q-property

class GameObject: public QObject{
    Q_OBJECT
    Q_PROPERTY(int game_width READ game_width WRITE set_game_width NOTIFY game_widthChanged)
    Q_PROPERTY(int game_height READ game_height WRITE set_game_height NOTIFY game_heightChanged)
public:
    using QObject::QObject;
    int game_width() const{
        return m_width;
    }
    void set_game_width(int width){

        if(width == m_width)
            return;
        m_width = width;
        emit game_widthChanged();
    }
    int game_height() const{
        return m_height;
    }
    void set_game_height(int height){
        if(height == m_height)
            return;
        m_height = height;
        emit game_heightChanged();
    }
signals:
    void game_widthChanged();
    void game_heightChanged();
private:
    int m_width;
    int m_height;
};

main.cpp

...
GameObject my_obj_here;

QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("my_obj_here", &my_obj_here);
...

main.qml

ApplicationWindow{


    Connections{
        target: contentItem
        onHeightChanged:
            my_obj_here.game_height = height
        onWidthChanged:
            my_obj_here.game_width = width
    }
    ...
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51223199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档