【QT入门学习】
通过类实例化创建对象——以QPushButton为例:
类在QT中的定义及说明——QPushButton的定义:
QPushButton Class//类名
The QPushButton widget provides a command button. More...
Header:
#include <QPushButton> //使用该类需要包含的头文件
qmake:
QT += widgets//该类所属的模块
Inherits://父类
QAbstractButton
Inherited By://子类
QCommandLinkButton
List of all members, including inherited members
Obsolete members
对象的定义——定义一个按钮:
#include <QPushButton>
......
QPushButton *userButton=new QPushButton;//类名 *变量名=new 类名
对象的显示方式——显示一个按钮:
1.显示在顶层——单独弹出一个窗口
userButton->show();//对象名->show()
运行效果如图:
2.显示在myWidget窗口中
userButton->setParent(this);//this是指向当前窗口的指针
运行效果如图:
文本的显示——在按钮上显示文字:
1.定义好按钮后再确定按钮内文字:
userButton->setText("BUTTON1");//""中为按钮中显示的文字
效果如图:
2.定义按钮时确定显示文字:
QPushButton *userButton2=new QPushButton("BUTTON2",this);//("按钮名称",显示位置指针)
效果如图:
位置的改变——改变按钮在myWidget窗口上的显示位置:
默认生成位置为(0,0),用move函数改变按钮位置:
userButton2->move(100,250);//将按钮的位置设定为100,250(指左上角第一个点的坐标)
效果如图:
扩展:
窗口大小的设定:
1.可改变的窗口大小——resize:
在这里插入代码片//resize分配容器内存大小,resize(宽,高)
运行效果如图:
2.固定窗口大小——setFixSize函数:
setFixedSize(600,400);//设定固定窗口大小,setFixedSize(宽,高)
运行效果如图:
固定大小后,窗口大小不可伸缩
窗口名称的设定——setWindowTitle函数:
setWindowTitle("QTWindow");//设置窗口名称
运行效果如图:
本节myWidget.cpp总代码如下:
#include "mywidget.h"
#include <qpushbutton.h>
myWidget::myWidget(QWidget *parent)
: QWidget(parent)
{
setFixedSize(600,400);//设定固定窗口大小,setFixedSize(宽,高)
//resize(500,500);//定义myWidget窗口大小
//setWindowTitle("QTWindow");//设置窗口名称
QPushButton *userButton1=new QPushButton;//定义按钮1
userButton1->setParent(this);//显示在当前对象窗口
//userButton1->show();
userButton1->setText("BUTTON1");//""中为按钮中显示的文字
QPushButton *userButton2=new QPushButton("BUTTON2",this);//定义按钮2
userButton2->move(100,250);//将按钮的位置设定为100,250(指左上角第一个点的坐标)
}
myWidget::~myWidget()
{
}