在小的时候,我们经常会看到程序员的表白链接或者表白软件,今天我们来用qt做一个简易版本,并复习一下窗口,信号与槽的操作
1.整体思路
在窗口中显示一个按钮,写着表白话语,然后两个按钮,yes和no,点no则该按钮就跑,点yes则出现约会话语,再点就关闭窗口
2.分布实现思路
表白按钮直接写,yes按钮要一个点击信号,槽的功能是出现约会话语按钮,no按钮则是根据随机数来改变按钮的位置
3.整体代码
可以给女朋友下一个qt creater然后复制过去,我的天好浪漫
pro
QT += core gui
QMAKE_PROJECT_DEPTH = 0greaterThan(QT_MAJOR_VERSION, 4): QT += widgetsCONFIG += c++17# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp \mainwindow.cppHEADERS += \mainwindow.hFORMS += \mainwindow.ui# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include<QPushButton>
#include<ctime>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();
public slots:void changeq1();void changeq2();private:Ui::MainWindow *ui;
public:QPushButton *q1;QPushButton*q2;};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);q1=new QPushButton("yes",this);q1->setGeometry(300,200,50,50);q2=new QPushButton("no",this);q2->setGeometry(450,200,50,50);std::srand(std::time(nullptr));connect(q1, &QPushButton::clicked, this, &MainWindow::changeq1);connect(q2, &QPushButton::clicked, this, &MainWindow::changeq2);
}void MainWindow::changeq1()
{QPushButton* q3=new QPushButton("have a dinner?",this);q3->setGeometry(250,500,300,100);q3->show();connect(q3, &QPushButton::clicked, this, &MainWindow::close);
}
void MainWindow:: changeq2()
{int x=std::rand()%100;int y=std::rand()%100;q2->setGeometry(x,y,50,50);
}
MainWindow::~MainWindow()
{delete ui;
}
main.cpp
#include "mainwindow.h"#include <QApplication>
#include<QObject>
#include<QPushButton>
int main(int argc, char *argv[])
{QApplication a(argc, argv);MainWindow w;QPushButton *q=new QPushButton("do you love me?",&w);q->setGeometry(300,300,200,100);w.show();return a.exec();
}