mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QDesktopWidget>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void InitWidget();
void resetGrid(QWidget *widget,double factorx,double factory);
private:
Ui::MainWindow *ui;
double factorx;//横向缩放比例
double factory;//纵向缩放比例
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#define INIT_SREEN_WID 1920.0 //初始化环境分辨率
#define INIT_SREEN_HEI 1080.0
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setFixedSize(1280, 800);
QFont font;
font.setFamily(QString::fromLocal8Bit("楷体"));
font.setPixelSize(90);
font.setBold(true);
ui->label->setFont( font );
InitWidget();
QFont ft = ui->label->font();
int fontsize = ft.pixelSize();
font.setPixelSize( fontsize * factory );
ui->label->setFont( font );
QObjectList q(ui->centralWidget->children());
for (int i = 0; i < q.length(); i++)
{
QObject* o = q.at(i);
if (o->inherits("QPushButton"))
{
QPushButton* b = qobject_cast<QPushButton*>(o);
resetGrid(b, factory, factory);
}
else if ( o->inherits("QLineEdit") )
{
QLineEdit* b = qobject_cast<QLineEdit*>(o);
resetGrid(b, factory, factory);
}
else if ( o->inherits("QComboBox") )
{
QComboBox* b = qobject_cast<QComboBox*>(o);
resetGrid(b, factory, factory);
}
else if ( o->inherits("QLabel") )
{
QLabel* b = qobject_cast<QLabel*>(o);
resetGrid(b, factory, factory);
}
}
qDebug() << "@@@:" << (double)ui->pushButton->width()/(double)ui->pushButton->height();
qDebug() << "###:" << (double)1280.0/(double)800.0;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::InitWidget()
{
int currentScreenWid = QApplication::desktop()->width();
int currentScreenHei = QApplication::desktop()->height();
qDebug() << currentScreenWid << "*" << currentScreenHei;
double ScreenWid = INIT_SREEN_WID;
double ScreenHei = INIT_SREEN_HEI;
factorx = (double)currentScreenWid/ScreenWid;
factory = (double)currentScreenHei/ScreenHei;
qDebug() << "factorx:" << factorx << "factory" << factory;
resetGrid(this, factory, factory);
}
void MainWindow::resetGrid(QWidget *widget,double factorx,double factory)
{
int widgetX = widget->x();
int widgetY = widget->y();
int widgetWid = widget->width();
int widgetHei = widget->height();
int nWidgetX = (int)(widgetX*factorx);
int nWidgetY = (int)(widgetY*factory);
int nWidgetWid = (int)(widgetWid*factorx);
int nWidgetHei = (int)(widgetHei*factory);
widget->setGeometry(nWidgetX,nWidgetY,nWidgetWid,nWidgetHei);
widget->setFixedSize(nWidgetWid, nWidgetHei);
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
w.move ((QApplication::desktop()->width() - w.width())/2,(QApplication::desktop()->height() - w.height())/2);
return a.exec();
}