Get Qt Widget Size: width() & height() Guide
In Qt, you can use the width() and height() functions of the QWidget class to get the width and height of a widget. Here is an example code:
#include <QApplication>
#include <QWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget widget;
widget.resize(200, 100);
widget.show();
int width = widget.width(); // 获取宽度
int height = widget.height(); // 获取高度
return a.exec();
}
In the code above, we created a QWidget object named widget and set its size to 200×100 pixels using the resize() function. We then used the width() and height() functions to retrieve the width and height of the widget respectively, and stored them in width and height variables. Finally, we started the event loop of the Qt application by calling the exec() function.
Please make sure the window is displayed before obtaining the size of the control, otherwise the width and height returned may be 0.