初识QT

第一个QT程序
#include <QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char **argv)
{
    QApplication zhuyuantan(argc, argv);//每个QT只能有一个QApplication对象
    QWidget mainWindow;//QWidget可看做一个窗口 ,在上面可以放置如按钮这样的对象
    //设置窗口mainWindow的最大像素和最小像素
    mainWindow.setMinimumSize(200, 100);
    mainWindow.setMaximumSize(200, 100);
    //创建按钮对象 调用构造函数 第一个参数告诉构造函数将按钮标签设置成"hello world!"
  // 第二个参数mainWindow作为父窗口
    QPushButton helloworld("hello world!", &mainWindow);
    //设置串口函数尺寸 这里是将按钮左上角放置在主窗口右边20像素下边20像素的位置
  //,后面两个参数设置按钮的宽度和高度(这里将其设置为160像素宽、60像素高)
    helloworld.setGeometry(20, 20, 160, 60);
    mainWindow.show(); //显示mainWindow,不用掉用hellword的show。mainWindow的show被调用时helloworld也会显示
    return zhuyuantan.exec(); //将控制权传给QT,在exec中QT接受和处理用户及系统事件。并把这些事件传递给相应的窗口,当程序关闭时,exec函数返回
}

 

Qt中使用类继承
创建QT更多用到类继承,编写QT应用程序大多时候是基于已有的Qt类编写用户类
#include <QApplication>
#include <QWidget>
class zhuyuantan : public QWidget
{
public:
    zhuyuantan();
};
zhuyuantan::zhuyuantan()
{
//设置未创建的主窗口对象的最大和最小像素
//这样设置的窗口将不能改变窗口大小
    this->setMinimumSize(200, 200);
    this->setMaximumSize(200, 200);
}
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    zhuyuantan w;
    w.show();
    return a.exec();
}

 

Qt向主部件添加对象
窗口上没有任何与用户交互的对象,那么程序也没有太大的用处
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QFont>
class MyMainWindow : public QWidget
{
public:
    MyMainWindow();
private:
    QPushButton *b1;
};
MyMainWindow::MyMainWindow()
{
    setGeometry(100, 100, 200, 120);
    b1 = new QPushButton("Button 1", this);
    b1->setGeometry(20, 20, 160, 80);
    //QPushButton::QFont:格式化按钮上的文本 函数用QFont对象作为参数 QFont的构造函数的三个参数---第一个表示字体、
    //第二个表示定义字体大小 第三个说明将文本加粗 最后一个参数也称为字体的粗细(Weight)。他将文本定义为粗体
    //还可以向构造函数增加第四个选项参数,它为布尔值,用于定义文本是否为斜体。
    // b1->setFont(QFont("Courier", 12, QFont::Light, true)); //这条语句将字体设置为Courier,大小为12像素,文本为细体(与粗体相反)和斜体
    //QFont font("Times", 18, QFont::Bold);//与下面语句相同但更容易理解
    //b1->setFont(font);
    b1->setFont(QFont("Times", 18, QFont::Bold));
}
int main(int argc, char** argv)
{
    QApplication a(argc, argv);
    MyMainWindow w;
    w.show();
    return a.exec();
}

 




posted @ 2021-05-24 21:31  朱元叹  阅读(87)  评论(0)    收藏  举报