QT5 第一个标签 按键

最近要设计GUI,顺带把C++深入学习下。

第一个标签显示和按键反应算是进入GUI设计的hello world吧。
在这里插入图片描述在这里插入图片描述
在工程文件里的三个分别写入
//main.cpp 写入

#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);


    MainWindow w;
    w.setWindowTitle("测试窗口");
    w.setGeometry(200,200,210,150);
    w.show();

    return a.exec();
}

//mainwindow.cpp 写入

#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)//构造器
    : QMainWindow(parent)
{
    label=new QLabel(tr("我是显示标签!!"),this);
    button=new QPushButton(tr("按我!!"),this);//实例化label,button控件
    label->setGeometry(50,50,100,50);
    button->setGeometry(50,90,80,40);//设置label以及button位置和大小

    connect(button,SIGNAL(clicked()),this,SLOT(command()));//响应的槽函数

}
void MainWindow::command()
{
    label->setText("我被按下去了!!");
}
MainWindow::~MainWindow()//析构器
{
}

//头文件mainwindow.h写入

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include<QPushButton>
#include<QLabel>
class MainWindow : public QMainWindow   //定义一个mainwindow类
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    QLabel *label;
    QPushButton *button;

private slots:
    void command();
};

#endif // MAINWINDOW_H

信号和槽机制:简单来说就是组件之间发出信号和相应连接该信号的槽之间响应。诸如用户点击和定时器等等信号。

信号与槽机制连接方式:
1.一个信号与一个信号相连:
*
connect(Object,SIGNAL(signal1),Object2,SIGNAL(signal1));

2.一个信号同多个槽相连:
*
connect(Object,SIGNAL(signal12),Object2,SIGNAL(slot2));
*
connect(Object,SIGNAL(signal12),Object3,SIGNAL(slot1));

3.同一个槽相应多个信号:
*
connect(Object1,SIGNAL(signal12),Object2,SIGNAL(slot2));
*
connect(Object3,SIGNAL(signal12),Object3,SIGNAL(slot2));

4.常用方式:
*
connect(Object1,SIGNAL(signal),Object2,SLOT(slot));

QT5 从入门到爱上控制台。

猜你喜欢

转载自blog.csdn.net/ocean35/article/details/86622688