您可以使用QDesktopWidget
类来获取桌面的长宽信息。以下是一个示例代码片段,演示如何使用QDesktopWidget
获取主屏幕的宽度和高度:
#include <QApplication>
#include <QDesktopWidget>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDesktopWidget *desktop = QApplication::desktop();
int screenWidth = desktop->screenGeometry().width();
int screenHeight = desktop->screenGeometry().height();
qDebug() << "Screen Width: " << screenWidth;
qDebug() << "Screen Height: " << screenHeight;
return app.exec();
}
通过调用screenGeometry()
函数可以获得主屏幕的几何信息,包括位置、大小等。然后,可以使用width()
和height()
函数分别获取宽度和高度。
请注意,在Qt 5之后,推荐使用QGuiApplication::primaryScreen()
和QScreen::geometry()
来获取屏幕信息。这种方法提供了更多灵活性,并且适用于多显示器环境下。
#include <QGuiApplication>
#include <QScreen>
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QScreen *primaryScreen = QGuiApplication::primaryScreen();
QRect screenGeometry = primaryScreen->geometry();
int screenWidth = screenGeometry.width();
int screenHeight = screenGeometry.height();
qDebug() << "Screen Width: " << screenWidth;
qDebug() << "Screen Height: " << screenHeight;
return app.exec();
}
以上两种方法都可以用来获取桌面的长宽信息。
内容由零声教学AI助手提供,问题来源于学员提问