Qt(三)

1.QLabel

1.1显示图片
1.1.1setPixmap(QPixmap(“😕…”))
1.2显示gif
1.2.1setMovie()
1.2.2new movie
1.2.3movie->start();

2.Combox

2.1setCurrentIndex(索引)
2.2setCurrentText(“拖拉机”)

3.自定义控件

3.1smallWidget 设计师界面类
3.2提升完了 使用
3.3信号和槽
3.3.1valueChanged
3.3.2setValue

01_SmallWidget
01_SmallWidget.pro

#-------------------------------------------------
#
# 
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 01_SmallWidget
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp \
    smallwidget.cpp

HEADERS  += widget.h \
    smallwidget.h

FORMS    += widget.ui \
    smallwidget.ui

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

smallwidget.h

#ifndef SMALLWIDGET_H
#define SMALLWIDGET_H

#include <QWidget>

namespace Ui {
class SmallWidget;
}

class SmallWidget : public QWidget
{
    Q_OBJECT

public:
    explicit SmallWidget(QWidget *parent = 0);
    ~SmallWidget();

    void setValue(int v);

    int getValue();


private:
    Ui::SmallWidget *ui;
};

#endif // SMALLWIDGET_H

smallwidget.cpp

#include "smallwidget.h"
#include "ui_smallwidget.h"

SmallWidget::SmallWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SmallWidget)
{
    ui->setupUi(this);

    //QSpinBox移动 Slider跟着移动
    void(QSpinBox:: * signal)(int) = &QSpinBox::valueChanged;
    connect(ui->spinBox,signal,ui->horizontalSlider,&QSlider::setValue);


    //Slider移动  SpinBox跟着移动
    connect(ui->horizontalSlider,&QSlider::valueChanged,ui->spinBox,&QSpinBox::setValue);

}

void SmallWidget::setValue(int v)
{
    ui->spinBox->setValue(v);
}

int SmallWidget::getValue()
{
    return ui->spinBox->value();

}

SmallWidget::~SmallWidget()
{
    delete ui;
}

smallwidget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>SmallWidget</class>
 <widget class="QWidget" name="SmallWidget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>199</width>
    <height>38</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QHBoxLayout" name="horizontalLayout">
   <item>
    <widget class="QSpinBox" name="spinBox"/>
   </item>
   <item>
    <widget class="QSlider" name="horizontalSlider">
     <property name="orientation">
      <enum>Qt::Horizontal</enum>
     </property>
    </widget>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Widget</class>
 <widget class="QWidget" name="Widget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>511</width>
    <height>366</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <widget class="SmallWidget" name="widget" native="true">
   <property name="geometry">
    <rect>
     <x>110</x>
     <y>50</y>
     <width>231</width>
     <height>80</height>
    </rect>
   </property>
  </widget>
  <widget class="QPushButton" name="btnGet">
   <property name="geometry">
    <rect>
     <x>180</x>
     <y>170</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>获取值</string>
   </property>
  </widget>
  <widget class="QPushButton" name="btnSet">
   <property name="geometry">
    <rect>
     <x>180</x>
     <y>210</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>设置到一半</string>
   </property>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <customwidgets>
  <customwidget>
   <class>SmallWidget</class>
   <extends>QWidget</extends>
   <header location="global">smallwidget.h</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>



Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //点击设置 到一半的位置

    connect(ui->btnSet,&QPushButton::clicked,[=](){
        ui->widget->setValue(50);
    });

    //点击获取,拿到当前值
    connect(ui->btnGet,&QPushButton::clicked,[=](){
        qDebug () << "当前值为:" << ui->widget->getValue();
    });
}

Widget::~Widget()
{
    delete ui;
}

4.事件

在这里插入图片描述
4.1鼠标进入 参数要加入
4.2鼠标离开
4.3鼠标按下
4.3.1位置信息 ev->x() ev->y()
4.3.2判断按键 ev->button() Qt::LeftButton
4.4鼠标释放
4.5鼠标移动
4.5.1判断按键 ev->buttons() & Qt::LeftBtton
02_Qt_Event
02_Qt_Event.pro

#-------------------------------------------------
#
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 02_Qt_Event
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp \
    mylabel.cpp

HEADERS  += widget.h \
    mylabel.h

FORMS    += widget.ui

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

mylabel.h

#ifndef MYLABEL_H
#define MYLABEL_H

#include <QLabel>

class MyLabel : public QLabel
{
    Q_OBJECT
public:
    explicit MyLabel(QWidget *parent = 0);


    //捕获事件
    //鼠标进入

    void enterEvent(QEvent *);

    //鼠标离开
    void leaveEvent(QEvent *);

    //鼠标按下
    void mousePressEvent(QMouseEvent *ev);
    //鼠标释放
    void mouseReleaseEvent(QMouseEvent *ev);
    //鼠标移动
    void mouseMoveEvent(QMouseEvent *ev);

    //事件分发 Event事件
    bool event(QEvent *e);

};

#endif // MYLABEL_H

mylabel.cpp

#include "mylabel.h"
#include <QDebug>
#include<QMouseEvent>
MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
{
    //设置鼠标追踪
   // this->setMouseTracking(true);
}


//鼠标进入

void MyLabel::enterEvent(QEvent *)
{
    //qDebug()  << "鼠标进入了!!!";

}

//鼠标离开
void MyLabel::leaveEvent(QEvent *)
{
    // qDebug()  << "鼠标离开了!!!";
}


//鼠标按下
void MyLabel::mousePressEvent(QMouseEvent *ev)
{

    //如果 鼠标按下的是左键,然后提示内容
    //找按下的 位置
//    if(ev->button() ==  Qt::LeftButton)
//    {
        QString str = QString("鼠标按下了!!! x = %1 y = %2").arg(ev->x()).arg(ev->y());

        qDebug()  << str;
//    }

}
//鼠标释放
void MyLabel::mouseReleaseEvent(QMouseEvent *ev)
{
//    if(ev->button() ==  Qt::LeftButton)
//    {
     QString str = QString("鼠标释放了!!! x = %1 y = %2").arg(ev->x()).arg(ev->y());
     qDebug()  << str;
//    }
}
//鼠标移动
void MyLabel::mouseMoveEvent(QMouseEvent *ev)
{
    //持续状态 需要用buttons  用与操作符 进行判断
//    if(ev->buttons() &  Qt::LeftButton)
//    {
     QString str = QString("鼠标移动了!!! x = %1 y = %2").arg(ev->x()).arg(ev->y());
     qDebug()  << str;
//    }
}

bool MyLabel::event(QEvent *e)
{
    //通常不会做拦截 ,event只要分发事件就可以了
   if( e->type() == QEvent::MouseButtonPress)
   {
       QMouseEvent * ev =  static_cast<QMouseEvent *>(e);

       QString str = QString("Event:::鼠标按下了!!! x = %1 y = %2").arg(ev->x()).arg(ev->y());

       qDebug()  << str;
        //只有鼠标按下 自己处理 返回true
       return true;
   }

   //其他事件 让父亲做默认处理
   return QLabel::event(e);
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;


    //定时器事件
    void timerEvent(QTimerEvent *);

    //定时器标识号
    int id1;
    int id2;

    //事件过滤器的事件
    bool eventFilter(QObject *, QEvent *);
};

#endif // WIDGET_H

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Widget</class>
 <widget class="QWidget" name="Widget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <widget class="MyLabel" name="label">
   <property name="geometry">
    <rect>
     <x>40</x>
     <y>20</y>
     <width>301</width>
     <height>51</height>
    </rect>
   </property>
   <property name="frameShape">
    <enum>QFrame::Box</enum>
   </property>
   <property name="text">
    <string/>
   </property>
  </widget>
  <widget class="QLabel" name="label_2">
   <property name="geometry">
    <rect>
     <x>40</x>
     <y>90</y>
     <width>291</width>
     <height>51</height>
    </rect>
   </property>
   <property name="frameShape">
    <enum>QFrame::Panel</enum>
   </property>
   <property name="text">
    <string/>
   </property>
  </widget>
  <widget class="QLabel" name="label_3">
   <property name="geometry">
    <rect>
     <x>50</x>
     <y>160</y>
     <width>271</width>
     <height>41</height>
    </rect>
   </property>
   <property name="frameShape">
    <enum>QFrame::WinPanel</enum>
   </property>
   <property name="text">
    <string/>
   </property>
  </widget>
  <widget class="QLabel" name="label_4">
   <property name="geometry">
    <rect>
     <x>40</x>
     <y>230</y>
     <width>271</width>
     <height>41</height>
    </rect>
   </property>
   <property name="frameShape">
    <enum>QFrame::Box</enum>
   </property>
   <property name="frameShadow">
    <enum>QFrame::Sunken</enum>
   </property>
   <property name="text">
    <string/>
   </property>
  </widget>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>320</x>
     <y>240</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>暂停</string>
   </property>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <customwidgets>
  <customwidget>
   <class>MyLabel</class>
   <extends>QLabel</extends>
   <header location="global">mylabel.h</header>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QTimerEvent>
#include <QTimer>
#include <QMouseEvent>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //启动定时器
    id1 = startTimer(1000); //每1000毫秒调用一次timerEvent事件
    id2 = startTimer(2000);

    //定时器第二种方式
    QTimer * timer1 = new QTimer(this);
    //启动定时器对象
    timer1->start(500); //毫秒做单位
    //每隔0.5秒发送信号
    connect(timer1,&QTimer::timeout,[=](){
        static int num = 0;
        ui->label_4->setText( QString::number(num++));
    });

    //点击按钮 暂停定时器
    connect(ui->pushButton,&QPushButton::clicked,[=](){
        timer1->stop();
    });



    //给ui->label做事件过滤器 拦截
    //步骤1  给控件安装过滤器
    // 参数this 通过父窗口给lable安装过滤器
    ui->label->installEventFilter(this);
    //步骤2  重写 eventFilter事件

}

bool Widget::eventFilter(QObject * obj, QEvent * e)
{
    if(obj == ui->label)
    {
        if( e->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent * ev =  static_cast<QMouseEvent *>(e);

            QString str = QString("事件过滤器:::鼠标按下了!!! x = %1 y = %2").arg(ev->x()).arg(ev->y());

            qDebug()  << str;
             //只有鼠标按下 自己处理 返回true
            return true;
        }
    }

    //其他让 父类处理
    return QWidget::eventFilter(obj,e);

}

void Widget::timerEvent(QTimerEvent * e)
{
    if(e->timerId() == id1)
    {
        static int num = 0;
        ui->label_2->setText( QString::number(num++));
    }

    if(e->timerId() == id2)
    {
        static int num2 = 0;
        ui->label_3->setText(QString::number(num2++));
    }

}

Widget::~Widget()
{
    delete ui;
}

5.定时器

5.1timerEvent
5.2启动 startTimer
5.3timerId
5.4第二种 QTimer
5.5启动 start
5.6timeout 信号
5.7stop 暂停

6.event

6.1作用 事件的分发
6.2返回值 bool
6.2.1作用 true 用户自己处理 ,不向下分发

7.事件过滤器 上层拦截

7.1安装事件过滤器
7.2重写eventfilter

8.QPainter

8.1QPainter painter(绘图设备 this)
8.2painter.draw…
8.3QPen pen(Qt::red); painter.setPen(pen); 画笔
8.4QBrush brush painter.setBrush()画刷
8.5高级绘图
8.5.1抗锯齿
8.5.2painter.setRenderHint(QPainter::Antialiasing);
8.5.3移动画家
8.5.4painter.translate(QPoint(100,0))
8.5.5保存画家状态
8.5.6painter.save
8.5.7取出状态
8.5.8painter.restore
8.6画图片
8.6.1drawPixmap( QPixmap( “ …png ”) );
8.7手动调用paintEvent
8.7.1update()

03_QPainter
03_QPainter.pro

#-------------------------------------------------
#
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 03_QPainter
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp

HEADERS  += widget.h

FORMS    += widget.ui

RESOURCES += \
    res.qrc

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;

public:
    //绘图事件
    void paintEvent(QPaintEvent *);

    int posX;

};

#endif // WIDGET_H

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Widget</class>
 <widget class="QWidget" name="Widget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>300</x>
     <y>250</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>移动</string>
   </property>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QPainter>


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //点击移动按钮 移动图片

    posX = 10;

    connect(ui->pushButton,&QPushButton::clicked,[=](){
        posX += 10;

        //手动调用绘图事件
        update();

    });

}

void Widget::paintEvent(QPaintEvent *)
{
    //创建画家
    QPainter painter(this);

    //如果出屏幕 强制变回10
    if(posX > this->width())
    {
        posX = 10;
    }

    //画图片
    painter.drawPixmap(posX,100,QPixmap(":/Image/OnePiece.png"));


    //高级设置
//    painter.drawEllipse( QPoint(100,100),50,50);
//    //设置抗锯齿 效率低
//    painter.setRenderHint(QPainter::Antialiasing);
//    painter.drawEllipse( QPoint(200,100),50,50);


//    painter.drawRect( QRect(20,20,50,50));

//    //移动画家
//    painter.translate(QPoint(100,0));

//    //保存状态
//    painter.save();

//    painter.drawRect( QRect(20,20,50,50));

//    painter.translate(QPoint(100,0));
//    //取出状态
//    painter.restore();

//    painter.drawRect( QRect(20,20,50,50));


//    //设置画笔颜色
//    QPen pen(QColor(255,0,0));
//    //设置笔宽度
//    pen.setWidth(3);
//    //设置笔风格
//    pen.setStyle(Qt::DotLine);
//    //画家用这只笔
//    painter.setPen(pen);

//    //画刷填充颜色
//    QBrush brush(Qt::cyan);
//    //让画家使用画刷
//    brush.setStyle(Qt::Dense4Pattern);
//    painter.setBrush(brush);


//    //利用画家画画
//    //画线
//    painter.drawLine(QPoint(0,0),QPoint(100,100));

//    //画圆(椭圆)
//    painter.drawEllipse(QPoint(100,100),50,50);

//    //画矩形
//    painter.drawRect(QRect(10,10,50,50));

//    //画字体
//    painter.drawText(QRect(10,200,150,50),"好好学习,天天向上");



}

Widget::~Widget()
{
    delete ui;
}

res.qrc

<RCC>
    <qresource prefix="/">
        <file>Image/butterfly.png</file>
        <file>Image/butterfly1.png</file>
        <file>Image/down.png</file>
        <file>Image/Frame.jpg</file>
        <file>Image/Luffy.png</file>
        <file>Image/LuffyQ.png</file>
        <file>Image/mario.gif</file>
        <file>Image/OnePiece.png</file>
        <file>Image/Sunny.jpg</file>
        <file>Image/sunny.png</file>
        <file>Image/up.png</file>
    </qresource>
</RCC>

9.绘图设备

9.1QPixmap pix(300,300)
9.2利用画家画图
9.3保存 save
9.4fill 填充颜色
9.5QImage img(300,300, …RGB32)
9.6画图
9.7保存 save
9.8对像素进行访问
9.8.1setPixel
9.9QBitmap
9.9.1色深 1 黑白色
9.10Qpicture
9.10.1绘图指令
9.10.2save 格式没有限定
9.10.3画图 进行加载 load
9.10.4painter.drawPicture(0,0,pic)

04_QPainterDevice
04_QPainterDevice.pro

#-------------------------------------------------
#
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 04_QPainterDevice
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp

HEADERS  += widget.h

FORMS    += widget.ui

RESOURCES += \
    res.qrc

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;


public:
    //绘图
    void paintEvent(QPaintEvent *);
};

#endif // WIDGET_H

widget.ui

<ui version="4.0">
 <class>Widget</class>
 <widget class="QWidget" name="Widget" >
  <property name="geometry" >
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle" >
   <string>Widget</string>
  </property>
 </widget>
 <layoutDefault spacing="6" margin="11" />
 <pixmapfunction></pixmapfunction>
 <resources/>
 <connections/>
</ui>

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QPicture>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //QPixmap 做绘图设备,对不同平台显示做了优化
//    QPixmap pix(300,300);
//    //设置默认填充色
//    pix.fill(Qt::white);
//    QPainter painter(&pix);

//    painter.setPen(QPen(Qt::green));
//    painter.drawEllipse(QPoint(150,150),100,100);
//    //保存
//    pix.save("E:\\pix.png");


    //QImage 做绘图设备  对像素级访问进行了优化
//    QImage img(300,300,QImage::Format_RGB32);
//    img.fill(Qt::white);
//    QPainter painter(&img);
//    painter.setPen(QPen(Qt::blue));
//    painter.drawEllipse(QPoint(150,150),100,100);
//    img.save("E:\\img.png");


    //QPicture 绘图设备
    QPicture pic; //用于重现 记录绘图指令
    QPainter painter;
    painter.begin(&pic);

    painter.setPen(QPen(Qt::cyan));
    painter.drawEllipse(QPoint(150,150),100,100);

    painter.end();
    //保存
    pic.save("E:\\pic.zt");


}

void Widget::paintEvent(QPaintEvent *)
{
    //QImage可修改xiangsu
//    QImage img;
//    img.load(":/Image/Luffy.png");

//    for(int i = 50 ; i < 100;i++)
//    {
//       for(int j = 50 ; j < 100 ;j ++)
//       {
//           QRgb value = qRgb(255,0,0);
//           //设置像素点
//            img.setPixel(i,j,value);
//       }
//    }

//    QPainter painter(this);
//    painter.drawImage(QPoint(0,0),img);


    //重现绘图指令 QPicture
    QPicture pic;
    pic.load("E:\\pic.zt");
    QPainter painter(this);
    painter.drawPicture(0,0,pic);

}

Widget::~Widget()
{
    delete ui;
}

res.qrc

<RCC>
    <qresource prefix="/">
        <file>Image/Luffy.png</file>
    </qresource>
</RCC>

10.QFile

10.1读 readAll 读取所有内容
10.2write 写
10.3默认编码 utf8

05_QFile
05_QFile.pro

#-------------------------------------------------
#
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 05_QFile
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp

HEADERS  += widget.h

FORMS    += widget.ui

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Widget</class>
 <widget class="QWidget" name="Widget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>413</width>
    <height>364</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <widget class="QWidget" name="widget" native="true">
     <layout class="QHBoxLayout" name="horizontalLayout">
      <item>
       <widget class="QLineEdit" name="lineEdit"/>
      </item>
      <item>
       <widget class="QPushButton" name="pushButton">
        <property name="text">
         <string>选择路径</string>
        </property>
       </widget>
      </item>
     </layout>
    </widget>
   </item>
   <item>
    <widget class="QTextEdit" name="textEdit"/>
   </item>
  </layout>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QTextCodec>
#include <QFileInfo>
#include <QDebug>
#include <QDateTime>
#include <QTextStream>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //点击按钮 选取文件
    connect(ui->pushButton,&QPushButton::clicked,[=](){

         QString path = QFileDialog::getOpenFileName(this,"打开文件","C:\\Users\\zhangtao\\Desktop");
         if(path.isEmpty())
         {
            QMessageBox::warning(this,"警告","打开失败");
         }
         else
         {
             //将路径 放入到lineEdit
             ui->lineEdit->setText(path);
             //读取文件
             //QFile默认支持UTF-8格式

             //QTextCodec * codec = QTextCodec::codecForName("gbk");

             QFile file(path); //参数路径名称
             //指定打开方式(只读)
             //file.open(QIODevice::ReadOnly);
             file.open(QFileDevice::ReadOnly);

             QByteArray array;
             array = file.readAll();

//             while( !file.atEnd())
//             {
//               array += file.readLine();
//             }

             //设置到 文本编辑框中
             ui->textEdit->setText(array);
             file.close();
             //读gbk
             // ui->textEdit->setText( codec->toUnicode(array));


             //写文件
             //重新指定打开方式
//             file.open(QFileDevice::Append);
//             file.write("哦哦哦哦哦哦");
//             file.close();

             //通过QFileInfo读取文件信息
               QFileInfo info(path);
               qDebug() << "路径: "<< info.filePath() << " 名称: "
                        <<info.fileName() << " 文件大小" << info.size() << "后缀名:"<<info.suffix();

               qDebug() << "创建日期:" <<info.created().toString("yyyy-MM-dd hh:mm:ss");
               qDebug() << "修改日期:" <<info.lastModified().toString("yyyy/MM/dd hh:mm:ss");
         }

    });



    //文件流读写文件
    //分类:文本流(基础数据类型) 和 数据流 (大型QImage)

    //文本流
//    QFile file("aaa.txt");
//    file.open(QFileDevice::WriteOnly);
//    QTextStream stream(&file);
//    stream<< QString("hello World") << 123456 ;
//    file.close();

//    //读取
//    file.open(QFileDevice::ReadOnly);
//    QString str;
//    //stream >>str; //读取空格 结束
//    str = stream.readAll();
//    qDebug() << str;

    //数据流 二进制
    QFile file("bbb.txt");
    file.open(QFileDevice::WriteOnly);
    QDataStream stream(&file);
    stream << QString("hello World") << 123456;
    file.close();

    //读数据
    file.open(QFileDevice::ReadOnly);
    QString str;
    int num;
    stream >>str >> num;
    qDebug() << str << num;

}

Widget::~Widget()
{
    delete ui;
}

11.QFileInfo

11.1文件信息
11.2// 大小 后缀名 文件名 文件路径
11.3qDebug() << info.size() <<info.suffix()<<info.fileName() << info.filePath();
11.4QDateTime toString

12.文件流

12.1文本流
12.1.1写 file.open(QIODevice::WriteOnly | QIODevice::Text)
12.1.2 readAll
12.2数据流
12.2.1dataStrema << QString(“hello world”)<<123456 数据块写入
12.2.2dataStrema >> str >> num 读时候也按照数据类型读取

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值