QT学习笔记(系统完整版)

自己跟着网上视频从头学一遍qt时记的笔记。

//命名规范:类名首字母大写,单词之间首字母大写,函数名变量名首字母小写,
//编译
//整行移动 ctrl+shift+↑或↓
//自动对其ctrl+i
//同名h和cpp切换 fn+f4
//查找关键字 ctrl+f
//帮助文档 fn+f1

//创建新按钮,基类选择QWiget,然后再在头文件和cpp里修改成QPushButton
 //按钮控件
    QPushButton * btn=new QPushButton;
  //  btn->show();//顶层方式显示

    //如果想显示时在当前窗口显示,需要设置父窗口
    btn->setParent(this);

    //设置文本
    btn->setText("你好");

    //创建第二个按钮
     QPushButton * btn2 =new QPushButton("hello",this);
    //按钮也可以重置尺寸
     btn2->resize(100,100);
     //移动位置
     btn2->move(100,300);

     //设置窗口尺寸
    // this->resize(100,200);

     //设置固定窗口尺寸
     this->setFixedSize(900,400);

     //设置窗口标题
     this->setWindowTitle("显示子女");

     //自定义自己的按钮,捕获析构函数
     MyPushButton *mybtn = new MyPushButton;
     mybtn->setParent(this);
     mybtn->move(200,300);
     mybtn->setText("我的按钮");

     //Qt中的坐标系
     //左上角(0,0)------>x
     //        |
     //        |
     //        y

     //信号和槽
     //connnect信号的发送者,发送的信号,信号的接收者,处理信号(槽函数)
     //点击按钮,实现关闭窗口
     //1.信号发送者(指针)2.发送的信号(地址)3.信号接收者(指针)4.处理信号/槽函数(地址)
     connect(mybtn,&MyPushButton::clicked,this,&Widget::close);

     //自定义信号和槽 见test2
//槽函数 写在 public slots下面,或者public/全局函数/lambda
    //1.返回值 void
    //2.需要声明,需要实现
    //3.可以有参,可以重载
 //自定义信号 写到 signals 下面
    //1.不需要返回值即void 2.只需要声明,不需要实现 3. 可以有参数,可以发生重载
  //QString 转为char*
    //1.调用toUtf8(),转为QByteArray
    //2.再调用data()转为char*
this->zt=new Teacher(this);
     this->st=new Student(this);

    //连接信号和槽
    //connect(this->zt,&Teacher::hungry,this->st,&Student::treat);

    //链接有参数的信号和槽
    //函数指针指向函数地址
//    void(Teacher::*teacherSignal)(QString)=&Teacher::hungry;
//    void(Student::*studentSlot)(QString)=&Student::treat;
//    connect(this->zt,teacherSignal,this->st,studentSlot);

    QPushButton * btn = new QPushButton;
    btn->setParent(this);
    btn->setText("下课");

    void(Teacher::*teacherSignal2)()=&Teacher::hungry;
    void(Student::*studentSlot2)()=&Student::treat;
    connect(this->zt,teacherSignal2,this->st,studentSlot2);

  connect(btn,&QPushButton::clicked,this->zt,teacherSignal2);
    //信号和槽拓展
    //1.信号连接信号
    //2.一个信号可以连接多个槽函数
    //3.多个信号可以绑定同一个槽函数
    //4.信号和槽的参数类型必须一一对应
    //5.信号的参数个数可以多于槽函数,但反之不可以,类型相同的参数类型也要一一对应包括位置上
    //6.可以利用disconnect 断开信号槽的链接
    disconnect(btn,&QPushButton::clicked,this->zt,teacherSignal2);
    //



    //调用下课函数
    classISOver();
}
 void Widget::classISOver()
 {
     //触发自定义信号
     emit this->zt->hungry();
     emit this->zt->hungry("宫保鸡丁");

 }

lambda

[函数对象参数] (操作符重载函数参数) mutable -> 返回值

{

函数体

}();

=最常用

//    connect(btn3,&QPushButton::clicked,this,[=]()
//    {
//       this->close(); 
//    });

// connect(mybtn,&MyPushButton::clicked,this,&Widget::close);

设置关闭也可以用lambda表达式实现,或者是以上

QMainWindow 提供主窗口程序 包括菜单栏 工具栏 锚接部件 状态栏 中心部件

一个用set  多个用add

 //重置窗口尺寸
    resize(600,400);

    //1.菜单栏 只能有一个
    QMenuBar *bar = menuBar();
    //将菜单栏设置到窗口中
    this->setMenuBar(bar);
    //添加菜单
    QMenu * fileMenu = bar->addMenu("文件");
    QMenu * fileMenu2 = bar->addMenu("编辑");
    //添加菜单项
    QAction * newAction=fileMenu->addAction("新建");
    //添加分割线
     fileMenu->addSeparator();
     QAction * openAction=fileMenu->addAction("打开");

     //菜单项中添加子菜单
     QMenu * subMenu = new QMenu;
     subMenu->addAction("子菜单1");
     subMenu->addAction("子菜单2");
     newAction->setMenu(subMenu);

     //2.工具栏 可以多个
     QToolBar *toolBar = new QToolBar(this);
     //将工具栏设置到窗口中 可以设置停靠区域
     addToolBar(toolBar);
     addToolBar(Qt::LeftToolBarArea,toolBar);
     //设置只允许左右停靠
     toolBar->setAllowedAreas(Qt::LeftToolBarArea|Qt::RightToolBarArea);
     //设置浮动
     toolBar->setFloatable(false);
     //设置移动
     toolBar->setMovable(false);
     //添加菜单项
     toolBar->addAction(newAction);
     //添加分割线
     toolBar->addSeparator();
     toolBar->addAction(openAction);

     //3.状态栏 只有一个
     QStatusBar * sBar =statusBar();
     setStatusBar(sBar);
     //左侧信息
     QLabel * label1 = new QLabel("左侧信息",this);
     sBar->addWidget(label1);
     //右侧信息
     QLabel * label2 = new QLabel("右侧信息",this);
     sBar->addPermanentWidget(label2);
     //指定位置插入
     QLabel * label3 = new QLabel("左侧信息2",this);
     sBar->insertWidget(0,label3);

     //4.锚接部件(浮动窗口) 可以多个 围绕核心进行转动
     QDockWidget * dock = new QDockWidget("浮动窗口",this);
     addDockWidget(Qt::BottomDockWidgetArea,dock);
     //设置只允许上和下 停靠
     dock->setAllowedAreas(Qt::TopDockWidgetArea|Qt::BottomDockWidgetArea);
     //5.核心部件(中心部件)
     QTextEdit * edit =new QTextEdit(this);
     setCentralWidget(edit);

添加资源文件

ui->setupUi(this);//放在构造的最上方
   // ui->actionnew->setIcon(QIcon ("D:\\图片\\2021240207\\QQ图片20220415192331.jpg"));

    //导入资源
    //1.将资源放入到项目下
    //2.添加资源文件
    //2.1右键项目 添加新文件 Qt resource file 起名如:resource 生成resource.qrc
    //3.编辑资源文件
    //3.1右键 open in editor 添加前缀 添加文件
    //4.使用资源
    //4.1语法: ":+前缀名+文件名"
    ui->actionnew->setIcon(QIcon(":/Saved Pictures/005NUVSBgy1gxabzamel1j32ip1f1x6p.jpg"));
    ui->actiondakai->setIcon(QIcon(":/Saved Pictures/006p8Yjmgy1gxadt0f7jkj31jk2bc1kx.jpg"));

模态对话框和非模态对话框

//点击新建,弹出对话框
    connect(ui->actionnew,&QAction::triggered,[=](){

        //对话框分类
        //模态对话框   弹出后,不可以对其他对话框进行操作 阻塞
        //非模态对话框 可以对其他对话框进行操作 不会阻塞

        //创建模态对话框
        QDialog dlg(this);
        dlg.resize(120,30);
        dlg.exec();
        //创建非模态对话框
        QDialog *dlg=new QDialog(this);//写到堆区
        dlg->resize(120,30);
        dlg->show();
        //设置属性
        dlg->setAttribute(Qt::WA_DeleteOnClose);//框关闭时释放空间
        qDebug()<<"弹出对话框";
        
        
        
   });

QMessageBox消息对话框

 connect(ui->actionnew,&QAction::triggered,[=](){//QMessageBox 消息对话框
   //错误提示 浮窗口 标题 文本
   QMessageBox::critical(this,"critical","错误!");
   //信息提示
   QMessageBox::information(this,"info","信息提示");
   //询问提示 参数1:父窗口 参数2:标题 参数3:中间显示文本 参数4:按键类型 参数5:关联回车按键
   QMessageBox::question(this,"question","提问",QMessageBox::Save | QMessageBox::Cancel,QMessageBox::Cancel);
   if (QMessageBox::Save== QMessageBox::question(this,"question","提问",QMessageBox::Save | QMessageBox::Cancel,QMessageBox::Cancel))
   {
       qDebug()<<"选择的是保存";
   }
   else  qDebug()<<"选择的是取消";

  //警告提示
  QMessageBox::warning(this,"warning","警告!");
  
  
  });

其他对话框

 //颜色对话框 没有加QColor函数默认是白色
        QColor color = QColorDialog::getColor(QColor(255,0,0));
        qDebug()<<color.red()<<color.blue()<<color.green();

        //字体对话框
        bool ok;
        QFont font=QFontDialog::getFont(&ok,QFont("华文彩云",10));
        qDebug()<<"字体"<<font.family()<<"字号"<<font.pointSize()<<"加粗"<<font.bold()<<"倾斜"<<font.italic();

        //文件对话框
        QString str= QFileDialog::getOpenFileName(this,"打开文件","D:\\1","(*.txt *.docx)");
        qDebug()<<str;

 界面布局

利用widgets做布局:水平、垂直、栅格

巧用弹簧进行设置

sizePolicy 垂直策略

 Layout 9像素间隙修改 

修改标题 尺寸等

常用控件 _按钮组  pushbutton(可以显示图标)、toolbutton(工具按钮 ,可以显示图标)、radiobutton(单选按钮)、checkbox(复选按钮)

 

//单选按钮默认选中男
    ui->radioButton_man->setChecked(true);
    //监听 用户选中女 的选项
    connect(ui->radioButton_woman,&QPushButton::clicked,[=](){

       sex=false;
    });
    connect(ui->radioButton_man,&QPushButton::clicked,[=](){

       sex=true;
    });
    connect(ui->pushButton_commit,&QPushButton::clicked,[=](){
    if(this->sex==true) qDebug()<<"提交男";
    else qDebug()<<"提交女";

    });

    //复选按钮
    //监听优美选项是否被选中 要么全用代码 要么全用属性 不要混在一起
    ui->checkBox->setTristate(true); // 第三种状态,半选中状态
    connect(ui->checkBox,&QCheckBox::stateChanged,[=](int status)
    {
        qDebug()<<status;//选中是2 未选中是0 半选是1
        
    });

QListWidget

//listWidget的使用
QListWidgetItem *item = new QListWidgetItem("锄禾日当午");
ui->listWidget->addItem(item);
//设置文本对齐方式  参数内容用帮助找
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

//QStringlist->QList<QString> 容器 不能设置对齐方式
QStringList list;
list<<"锄禾日当午"<<"汗滴禾下土"<<"谁知盘中餐"<<"粒粒皆辛苦";
ui->listWidget->addItems(list);

QTreeWidget

 //tableWidget的使用

    //1.设置列数
    ui->tableWidget->setColumnCount(3);
    //2.设置水平表头的标签
    ui->tableWidget->setHorizontalHeaderLabels(QStringList()<<"姓名"<<"职业"<<"魔法类型");
    //3.设置行数
     ui->tableWidget->setRowCount(5);
    // ui->tableWidget->setItem(0,0, new QTableWidgetItem("王不留行"));

     QStringList nameList;
     nameList<<"王不留行"<<"一叶知秋"<<"包子入侵"<<"寒烟柔";
     QList<QString> sexList;
     sexList<<"辅助"<<"法师"<<"流氓"<<"法师";
     for(int i=0;i<4;i++)
     {

         int col=0;
         ui->tableWidget->setItem(i,col++, new QTableWidgetItem(nameList[i]));
          ui->tableWidget->setItem(i,col++, new QTableWidgetItem(sexList.at(i)));
          //int转成 QString QString::number(18+i)
          ui->tableWidget->setItem(i,col++, new QTableWidgetItem(QString::number(18+i)));

     }
     //点击添加赵云 删除赵云
     connect(ui->btn_add,&QPushButton::clicked,[=](){

         bool isEmpty = ui->tableWidget->findItems("赵云",Qt::MatchExactly).isEmpty();
         if(!isEmpty)
         {
             QMessageBox::warning(this,"警告","赵云角色已有");
         }
         else
         {
             ui->tableWidget->insertRow(0);
             ui->tableWidget->setItem(0,0,new QTableWidgetItem(QString("赵云")));
             ui->tableWidget->setItem(0,1,new QTableWidgetItem(QString("肉坦")));
             ui->tableWidget->setItem(0,2,new QTableWidgetItem(QString::number(34)));
         }

     });
     connect(ui->btn_del,&QPushButton::clicked,[=](){
          bool isEmpty = ui->tableWidget->findItems("赵云",Qt::MatchExactly).isEmpty();
         if(isEmpty)
         {
             QMessageBox::warning(this,"警告","没有赵云角色");
         }
         else
         {
            int rowNum= ui->tableWidget->findItems("赵云",Qt::MatchExactly).first()->row();
            ui->tableWidget->removeRow(rowNum);
         }

     });
}

其他常用控件

//stack Widget
    //设置默认第一个
    ui->stackedWidget->setCurrentIndex(0);
    connect(ui->btn_1,&QPushButton::clicked,[=]()
    {
        //设置当前索引
        ui->stackedWidget->setCurrentIndex(0);
    });
    connect(ui->btn_2,&QPushButton::clicked,[=]()
    {
        //设置当前索引
        ui->stackedWidget->setCurrentIndex(1);
    });
    connect(ui->btn_3,&QPushButton::clicked,[=]()
    {
        //设置当前索引
        ui->stackedWidget->setCurrentIndex(2);
    });

    //comboBox 下拉框
    ui->comboBox->addItem("奔驰");
    ui->comboBox->addItem("宝马");

    //点击宝马按钮 就定位到宝马选项  设置索引或者文本
    connect(ui->btn_4,&QPushButton::clicked,[=](){
        //ui->comboBox->setCurrentIndex(1);
        ui->comboBox->setCurrentText("宝马");
    });

    //利用Qlabel显示图片
    QPixmap pix;
    pix.load(":Saved Pictures\\1.jpg");

    ui->label->setPixmap(QPixmap(pix));
    ui->label->setFixedSize(pix.width(),pix.height());

    //利用Qlabel显示gif动图
    QMovie *movie = new QMovie(":Saved Pictures\\1.gif");
    ui->label->setMovie(movie);
    movie->start();
    //设置速度
    movie->setSpeed(300);
    //设置播放结束停止  帧数会在变
    connect(movie,&QMovie::frameChanged,[=](int frameId){
        if(frameId == movie->frameCount()-1)
        {
            movie->stop();
        }
    });

Qt文件读写

//点击 选择文件按钮 弹出文件对话框,读取桌面文件,并且将文件的路径放入lineEdit中,文件内容放入TextEdit中
    connect(ui->pushButton,&QPushButton::clicked,[=](){
        QString filePath =QFileDialog::getOpenFileName(this,"打开文件","C:\\Users\\86198\\Desktop");
        if(filePath.isEmpty())
        {
            QMessageBox::warning(this,"警告","路径不能为空");
        }
        else
        {
            ui->lineEdit->setText(filePath);

            //指定编码格式
           // QTextCodec *codec = QTextCodec::codecForName("gbk");
            //读取文件信息
            QFile file(filePath);
            //指定打开方式
            file.open(QIODevice::ReadOnly);
            QByteArray arr;
            arr = file.readAll();//读取全部信息

            //读取单行数据
          //  arr=file.readLine();
//            while(!file.atEnd())
//            {
//                 arr += file.readLine();
//            }
            //qt默认支持utf-8格式
            ui->textEdit->setText(arr);
            //把arr数据转成指定的gbk格式
           //  ui->textEdit->setText(codec->toUnicode(arr));

            //关闭文件
            file.close();
            //
            file.open(QIODevice::Append);
            file.write("好好吃");
           

        }
    });

文件信息读取

//文件信息读取
            QFileInfo info(filePath);
            qDebug()<<"后缀名:"<<info.suffix().toUtf8().data()<<"大小:"<<info.size()
                   <<"文件名:"<<info.fileName()<<"文件路径:"<<info.filePath();
            qDebug()<<"创建日期:"<<info.created().toString("yyyy-MM-dd hh::mm::ss");
            qDebug()<<"最后修改日期:"<<info.lastModified().toString("yyyy-MM-dd hh::mm::ss");

以上。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值