QT学习笔记(四)——应用实例:计算器设置

一、界面分析:

二、相关组件介绍

2.1 QLineEdit组件

作用:1. 用于接受用户输入; 2.能够获取用户输入的字符串;3.是功能性组件需要父组件作为容器; 4.能够在父组件中进行定位

QWidget w;                                       //生成QWidget对象,顶级组件

QLineEdit le(&w);                              //生成QLineEdit对象,其父组件为QWidget

le.setAlignment(Qt::AlignRight);         //设置显示的字符串向右边对齐

le.move(10,10);                                  //移动到坐标(10,10);

le.resize(240, 30);                              //设置大小width =240,heigth = 30

三、设计与实现 :在程序开发前应该先进行界面设计

  • 界面设计:在程序编写前进行

         ——定义组件间的间隔

                        Space = 10px;

         ——定义按钮组件的大小

                        Width = 40px,Height = 40px

         ——定义文本框组件的大小

                        Width = 5 * 40px + 4 * 10px, Height = 30px

初步的程序:

#include "calculator.h"
#include <QtWidgets/QApplication>
#include <QWidget>
#include <QLineEdit>
#include <qpushbutton.h>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	QWidget *w = new QWidget; //创建父组件
	
	QLineEdit *le = new QLineEdit(w);//创建文本编译框
	le -> move(10, 10);
	le->resize(240, 30);

	QPushButton *button[20] = { 0 };//创建按钮
	const char *btnText[20] =
	{
		"7", "8", "9", "+", "(",
		"4", "5", "6", "-", ")",
		"1", "2", "3", "*", "<-",
		"0", ".", "=", "/", "C",
	};

	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 5; j++)
		{
			button[i * 5 + j] = new QPushButton(w);
			button[i * 5 + j] -> resize(40, 40);
			button[i * 5 + j] -> move(10 + (10 + 40) * j, 50 + (10 + 40) * i);
			button[i * 5 + j] -> setText(btnText[i * 5 + j]);
		}
	}

	w -> show();
	return a.exec();
}

结果:

但此时的结果有3个问题: 解决办法:
1.计算器程序不需要最大化和最小化按钮

在创建父窗口处加上:窗口关闭函数“NULL,Qt::WindowCloseButtonHint

即 QWidget *w = new QWidget(NULL,Qt::WindowCloseButtonHint);

2.计算器程序的窗口应该是固定大小 w->setFixedSize(w -> width(), w -> height());//固定窗口的大小
3.文本框不能直接输入字符 le->setReadOnly(true);//将文本框设置为只读模式

对窗口做了一定限制:

#include "calculator.h"
#include <QtWidgets/QApplication>
#include <QWidget>
#include <QLineEdit>
#include <qpushbutton.h>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	QWidget *w = new QWidget(NULL,Qt::WindowCloseButtonHint); //1.创建父组件 5.加(NULL,Qt::WindowCloseButtonHint)限制窗口的最大最小化
	
	QLineEdit *le = new QLineEdit(w);//2.创建文本编译框
	le -> move(10, 10);
	le->resize(240, 30);
	le->setReadOnly(true);//7.将文本框设置为只读模式

	QPushButton *button[20] = { 0 };//3.创建按钮
	const char *btnText[20] =        //4.为按键加字符
	{
		"7", "8", "9", "+", "(",
		"4", "5", "6", "-", ")",
		"1", "2", "3", "*", "<-",
		"0", ".", "=", "/", "C",
	};

	for (int i = 0; i < 4; i++)  //3.创建按钮
	{
		for (int j = 0; j < 5; j++)
		{
			button[i * 5 + j] = new QPushButton(w);
			button[i * 5 + j] -> resize(40, 40);
			button[i * 5 + j] -> move(10 + (10 + 40) * j, 50 + (10 + 40) * i);
			button[i * 5 + j] -> setText(btnText[i * 5 + j]);
		}
	}

	w -> show();
	w->setFixedSize(w -> width(), w -> height());//6.固定窗口的大小
	return a.exec();
}

结果:

小结:

猜你喜欢

转载自blog.csdn.net/qq_37764129/article/details/81429640