在C++中获取应用程序窗口的大小
Get Size of ApplicationWindow in C++
如何在C++中获取QML应用程序窗口的大小?
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();
我意识到我也没有获得应用程序窗口内容的大小(减去工具栏、菜单栏等(,但我如何访问它?
尝试使用property
方法访问window_object
上的window
属性将返回 null 指针。
一种可能的解决方案是使用QQmlProperty
来获取QQuickItem
,然后heightChanged
和widthChanged
信号连接,这些信号只通知属性已更改但不指示值,因此必须使用方法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;
};
主.cpp
...
GameObject my_obj_here;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("my_obj_here", &my_obj_here);
...
主.qml
ApplicationWindow{
Connections{
target: contentItem
onHeightChanged:
my_obj_here.game_height = height
onWidthChanged:
my_obj_here.game_width = width
}
...
相关文章:
- 如何将一个窗口保留在另一个应用程序窗口的前面
- 如何从 Win32 C++ 应用程序输出到父控制台窗口?
- 从运行服务的应用程序代码中提取窗口句柄
- 没有运算符"="与这些操作数匹配,JUCE 窗口演示应用程序
- 如何使用C++确定应用程序是否已在窗口中启动?
- 是否可以从控制台应用程序使用 C++/WinRT 创建窗口?
- 用C++编写.Net窗口应用程序
- 如何将 QML 文件分配给主窗口/应用程序
- 将WM_CHANGEUISTATE发送到窗口应用程序后,当用鼠标访问菜单时,助记符不会显示在系统菜单上
- MSBuild 未在控制台窗口应用程序中使用 "system" 进行编译
- QT通过单击Menubar C 移动整个窗口/应用程序
- 从控制台应用程序启动窗口应用程序
- 如何在QML无窗口应用程序中设置拖放区域
- 如何覆盖其他窗口应用程序的元素?
- 使用MINGW在窗口应用程序中压制系统("command")控制台窗口
- 将二维数组 double[][] 传递给 c# 窗口应用程序
- OpenGL窗口应用程序检查事件更新的频率
- 使用C++窗口应用程序加载Linux格式的文本文件
- 是否可以编写一个windows应用程序,当在另一个窗口应用程序中选择文本时,该应用程序会收到通知
- 如何使用c++ /Qt5构建无窗口应用程序?