QT学习之路DAY1之初学QT的小项目

以下所有代码均利用软件QT5编写

项目一:Hello world!

利用QTcreator创建项目

修改main.cpp代码为

 1 #include "mainwindow.h"
 2 #include <QApplication>
 3 #include <QLabel>
 4 
 5 int main(int argc, char *argv[])
 6 {
 7     QApplication a(argc, argv);
 8     QLabel *label = new QLabel("Hello, world!");
 9     label->show();
10 
11     return a.exec();
12 }
View Code

运行即可

QT学习之路DAY1之初学QT的小项目

 让Hello变为红色

改变main.cpp的代码

#include "mainwindow.h"
#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QLabel *label = new QLabel("<h2><font color='red'>Hello</font>, world! <h2>");
    label->show();

    return a.exec();
}
View Code

QT学习之路DAY1之初学QT的小项目

项目二:使用信号槽

还是改变main.cpp

//信号槽

#include "mainwindow.h"
#include <QApplication>
#include <QPushButton>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QPushButton *button = new QPushButton("Quit");
    QObject::connect(button,SIGNAL(clicked()),&a,SLOT(quit()));
    //connect是一个用于连接信号槽的静态函数
    button->show();

    return a.exec();
}
View Code

QT学习之路DAY1之初学QT的小项目

效果就是按下QUIT后退出

项目三:创建一个滑动杆和微调器并且连接起来

还是修改main.cpp

#include <QWidget>
#include <QSpinBox>
#include <QSlider>
#include <QHBoxLayout>
int main(int argc, char *argv[])
{
        QApplication app(argc, argv);
        QWidget *window = new QWidget;//创建窗口
        window->setWindowTitle("Enter your age");//设置窗口标题
        QSpinBox *spinBox = new QSpinBox;//创建上下箭头微调器
        QSlider *slider = new QSlider(Qt::Horizontal);//创建滑动杆
        spinBox->setRange(0, 130);//设置微调器范围
        slider->setRange(0, 130);//设置滑动杆范围
        QObject::connect(slider, SIGNAL(valueChanged(int)), spinBox,
SLOT(setValue(int)));//利用槽函数连接
        QObject::connect(spinBox, SIGNAL(valueChanged(int)), slider,
SLOT(setValue(int)));//利用槽函数连接
        spinBox->setValue(35);//设置初始值
        QHBoxLayout *layout = new QHBoxLayout;//水平布局
        /*  QHBoxLayout- 按照水平方向从左到右布局;
            QVBoxLayout- 按照竖直方向从上到下布局;
            QGridLayout- 在一个网格中进行布局,类似于 HTML 的 table。*/
        layout->addWidget(spinBox);//添加子布局
        layout->addWidget(slider);
        window->setLayout(layout);
        window->show();
        return app.exec();
}
View Code

QT学习之路DAY1之初学QT的小项目

相关推荐