qt 5

c++风格


qtcreator必须掌握的快捷键
1.ctrl+tab切换打开的窗口
2.alt+enter在.cpp里面快速添加定义
3.ctrl+shift 修改相同变量
4.ctrl+m书签,ctrl+.转到书签
5.ctrl+e+2/3/1分栏显示
6.f4/f2/ctrl+shift+up(down)/ctrl+i
头文件
  • 自给自足原则

用户和重构工具不需要为特别场合而包含额外的头文件。

  • #define保护
#ifndef FOO_BAR_BAZ_H_
#define FOO_BAR_BAZ_H_
...
#endif // FOO_BAR_BAZ_H
  • 尽量避免前置声明

waht is 前置声明?

class Date 
{  
    private:  
        int year, month, day;  
};  
//if want to use this class ,have two ways:
//one前置声明
class Date;  
class Task1 
{  
    public:  
        Date getData();  
};  
//two包含头文件
#include "Date.h"  
class Task2
{  
    public:  
        Date getData();  
};  
  • 慎用内联函数

在函数很短,可以内联,但是得保证此函数很少被调用

  • include的路径和顺序
#include <zylg.h>// find it on system first
#include "zylg.h"//find it on project first
作用域
#ifndef MYTEST_H
#define MYTEST_H
#include<iostream>
const int i=5;//内链接的特性,可以让其他的文件重新定义i(假如其他的问价include这个文件,当然也可以直接使用)
namespace zylg
{
    void s();
    namespace//让其具有内部链接性,相当于static后的一大块区域
    {
        void s1(){std::cout<<"my is inline namespace function,as  in static area,\n other file don`t use me\n";}
    }


};
#endif // MYTEST_H



#include<iostream>
using namespace std;
int i=9;
void s1()
{
    cout<<"how are you";
}
int main(int argc, char *argv[])
{
    s1();
   return 0;
}

1.匿名的命名空间会把空间里面的定义的东西自动放在上一级命名空间,比如上述代码可以zylg::s1(),这样保证了全局变量的名称资源(因为具有内部链接性),同时节约了命名空间数量

2.局部变量
将函数变量尽可能至于最小的作用域

3.全局变量和静态变量尽可能在控制范围内,少用

1.不要在构造函数里面调用虚函数,也不要在无法报出错误时进行可能失败的初始化.


2.不要定义隐式类型转换. 对于转换运算符和单参数构造函数, 请使用 explicit 关键字.别让int默默的就double了,explicit可以保证函数不会发生隐式转换,涉及类型转换的应该加上


3.可拷贝类型和可移动类型
如果你的类型需要, 就让它们支持拷贝 / 移动. 否则, 就把隐式产生的拷贝和移动函数禁用.

// MyClass is neither copyable nor movable.
MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;

4.结构体
仅当只有数据成员时使用 struct, 其它一概使用 class.


继承
使用组合 (YuleFox 注: 这一点也是 GoF 在 <> 里反复强调的) 常常比使用继承更合理. 如果使用继承的话, 定义为 public 继承.

//介绍组合模式
class component
{
//声明全部你所要用到的函数,在此处为虚函数,不去定义
}
class composite:public component
{
//实现虚函数全部
}
class left:public component
{
//实现个别的虚函数
}
/*
*在继承的时候,析构函数声明为虚函数,不然会发生内存泄露
*/

6.多重继承
真正需要用到多重实现继承的情况少之又少. 只在以下情况我们才允许多重继承: 最多只有一个基类是非抽象类; 其它基类都是以 Interface 为后缀的 纯接口类.


7.接口
接口是指满足特定条件的类, 这些类以 Interface 为后缀 (不强制).


8.运算符重载
除少数特定环*, 不要重载运算符. 也不要创建用户定义字面量.


9.存取控制
将 所有 数据成员声明为 private, 除非是 static const 类型成员 (遵循 常量命名规则). 处于技术上的原因, 在使用 Google Test 时我们允许测试固件类中的数据成员为 protected.


10.声明顺序
类定义一般应以 public: 开始, 后跟 protected:, 最后是 private:. 省略空部分.

函数

1.函数参数顺序
函数的参数顺序为: 输入参数在先, 后跟输出参数.


  1. 编写简短函数,我们倾向于编写简短, 凝练的函数.

3.引用参数
所有按引用传递的参数必须加上 const.
as:void Foo(const string &in, string *out);


4.函数重载
若要使用函数重载, 则必须能让读者一看调用点就胸有成竹, 而不用花心思猜测调用的重载函数到底是哪一种. 这一规则也适用于构造函数.


5.只允许在非虚函数中使用缺省参数, 且必须保证缺省参数的值始终一致. 缺省参数与 函数重载 遵循同样的规则. 一般情况下建议使用函数重载, 尤其是在缺省函数带来的可读性提升不能弥补下文中所提到的缺点的情况下.

study for google

1.所有权与智能指针,动态分配出的对象最好有单一且固定的所有主, 并通过智能指针传递所有权.
所有权是一种登记/管理动态内存和其它资源的技术. 动态分配对象的所有主是一个对象或函数, 后者负责确保当前者无用时就自动销毁前者. 所有权有时可以共享, 此时就由最后一个所有主来负责销毁它. 甚至也可以不用共享, 在代码中直接把所有权传递给其它对象.
智能指针是一个通过重载 * 和 -> 运算符以表现得如指针一样的类. 智能指针类型被用来自动化所有权的登记工作, 来确保执行销毁义务到位. std::unique_ptr 是 C++11 新推出的一种智能指针类型, 用来表示动态分配出的对象的独一无二的所有权; 当 std::unique_ptr 离开作用域时, 对象就会被销毁. std::unique_ptr 不能被复制, 但可以把它移动(move)给新所有主. std::shared_ptr 同样表示动态分配对象的所有权, 但可以被共享, 也可以被复制; 对象的所有权由所有复制者共同拥有, 最后一个复制者被销毁时, 对象也会随着被销毁.


2.cppplint
使用 cpplint.py 检查风格错误.

else study
1.所有按引用传递的参数必须加上const.
2.只在定义移动构造函数与移动赋值操作时使用右值引用. 不要使std::forward.
3.若要用好函数重载,最好能让读者一看调用点(call site)就胸有成竹,不用花心思猜测调用的重载函数到底是哪一种。该规则适用于构造函数。
4.我们不允许使用缺省函数参数,少数极端情况除外。尽可能改用函数重载。
5.我们不允许使用变长数组alloca().
6.我们允许合理的使用友元类及友元函数.
7.我们不使用 C++ 异常.
8.我们禁止使用 RTTI.在运行时判断类型通常意味着设计问题. 如果你需要在运行期间确定一个对象的类型, 这通常说明你需要考虑重新设计你的类
9.使用 C++ 的类型转换, 如 static_cast<>(). 不要使用 int y = (int)x 或 int y = int(x) 等转换方式;
10.只在记录日志时使用流.不要使用流,除非是日志接口需要. 使用 printf 之类的代替.使用流还有很多利弊, 但代码一致性胜过一切. 不要在代码中使用流.
11.对于迭代器和其他模板对象使用前缀形式 (++i) 的自增, 自减运算符.
12.我们强烈建议你在任何可能的情况下都要使用 const. 此外有时改用 C++11 推出的 constexpr 更好。
13.整形int16_t.如果您的变量可能不小于 2^31 (2GiB), 就用 64 位变量比如 int64_t. 此外要留意,哪怕您的值并不会超出 int 所能够表示的范围,在计算过程中也可能会溢出。所以拿不准时,干脆用更大的类型。
14.可移植性,代码应该对 64 位和 32 位系统友好. 处理打印, 比较, 结构体对齐时应切记
15.使用宏时要非常谨慎, 尽量以内联函数, 枚举和常量代替之.
16.nullptr 和 NULL,整数用 0, 实数用 0.0, 指针用 nullptr 或 NULL, 字符 (串) 用 '\0'.
17.尽可能用 sizeof(varname) 代替 sizeof(type).
18.auto 绕过烦琐的类型名,只要可读性好就继续用,别用在局部变量之外的地方。
19.适当使用 lambda 表达式。别用默认 lambda 捕获,所有捕获都要显式写出来。
20.只使用 Boost 中被认可的库.
命名规则

函数命名, 变量命名, 文件命名要有描述性; 少用缩写.

//文件命名:文件名要全部小写, 可以包含下划线 (_) 或连字符 (-), 依照项目的约定. 如果没有约定, 那么 “_” 更好.
//类型名命名:类型名称的每个单词首字母均大写, 不包含下划线
//变量名:变量 (包括函数参数) 和数据成员名一律小写, 单词之间用下划线连接,类变量以下划线结尾
//常量名:声明为 constexpr 或 const 的变量, 或在程序运行期间其值始终保持不变的, 命名时以 “k” 开头, 大小写混合
//函数名;规函数使用大小写混合, 取值和设值函数则要求与变量名匹配
//命名空间:命名空间以小写字母命名. *命名空间的名字取决于项目名称
//枚举;枚举的命名应当和 常量 或 宏 一致: kEnumName 或是 ENUM_NAME.
注释

使用 // 或 /* */, 统一就好.


在每一个文件开头加入版权公告.描述了该文件的内容


每个类的定义都要附带一份注释, 描述类的功能和用法, 除非它的功能相当明显.


通常变量名本身足以很好说明变量用途. 某些情况下, 也需要额外的注释说明.

//注:注释别写一些谁看函数都能看出来的废话,不如不写
格式
//1.每一行代码字符数不超过 80.
//2.尽量不使用非 ASCII 字符, 使用时必须使用 UTF-8 编码.
//3.倾向于不在圆括号内使用空格. 关键字 if 和 else 另起一行.
//4.switch 语句可以使用大括号分段, 以表明 cases 之间不是连在一起的. 在单语句循环里, 括号可用可不用. 空循环体应使用 {} 或 continue.
//5.不要在 return 表达式里加上非必须的圆括号.
//6.访问控制块的声明依次序是 //7.public:, protected:, private:, 每个都缩进 1 个空格.
//8.命名空间内容不缩进.

pro文件详解

TAMPLATE

描述为建立目标文件而采用的模板,即生成何种makefile文件
a.app(应用程序)
b.lib(库文件)
c.subdirs(子工程)
d.vcapp(仅用于windows的应用程序)
e.vclib

HEADERS

所有头文件列表

SOURCES

源文件列表

FORMS / INTERFACES

ui文件列表

LEXSOURCES

lex源文件列表

YACCSOURCES

yacc源文件列表

TARGET

可执行应用程序名称

DESTDIR

放置可执行目标的目录

DEFINES

应用程序所需的额外的预处理程序定义的列表。

INCLUDEPATH

应用程序所需的额外的包含路径的列表(include文件路径列表)。

DEPENDPATH

应用程序所依赖的搜索路径(描述了建立应用程序所依赖的其他文件所在的路 径)。

VPATH

寻找补充文件的搜索路径。

DEF_FILE

只有Windows需要:应用程序所要连接的.def文件。

C_FILE

只有Windows需要:应用程序的资源文件。

RES_FILE

只有Windows需要:应用程序所要连接的资源文件。

CONFIG变量

配置变量指定了编译器所要使用的选项和所需要被连接的库。配置变量中可以添加任何东西,但只有下面这些选项可以被qmake识别。

下面这些选项控制着使用哪些编译器标志:

release - 应用程序将以release模式连编。如果“debug”被指定,它将被忽略。

debug - 应用程序将以debug模式连编。

warn_on - 编译器会输出尽可能多的警告信息。如果“warn_off”被指定,它将被忽略。

warn_off - 编译器会输出尽可能少的警告信息。
qt - 应用程序是一个Qt应用程序,并且Qt库将会被连接。

thread - 应用程序是一个多线程应用程序。

x11 - 应用程序是一个X11应用程序或库。

windows - 只用于“app”模板:应用程序是一个Windows下的窗口应用程序。

console - 只用于“app”模板:应用程序是一个Windows下的控制台应用程序。

dll - 只用于“lib”模板:库是一个共享库(dll)。

staticlib - 只用于“lib”模板:库是一个静态库。

plugin - 只用于“lib”模板:库是一个插件,这将会使dll选项生效。

因为还用不到高级的,那这些就够用了
资源文件

<RCC>
    <qresource prefix="/image">
        <file>wz.jpg</file>
        <file>wz2.jpg</file>
    </qresource>
    <qresource prefix="/pictrue">
        <file>wz.jpg</file>
        <file>resourcefile.qrc</file>
        <file>wz2.jpg</file>
    </qresource>
</RCC>
/*
*Add New File -> Qt Resource File
*列出的资源文件必须位于 .qrc 文件所在目录或其子目录。
*/
//use ways
QMovie *movie =new QMovie(":/image/wz.jpg");

元对象系统


元对象系统提供了信号与槽机制

1.QObject类,为objects提供了一个可以利用元对象系统的基类。
2.Q_OBJECT宏: 在类的私有部分声明这个宏可以启用元对象特性,例如:动态属性、信号与槽。
3.Meta-Object编译器(moc): 为每个QObject子类生成必要的代码来实现元对象特性。
moc工具会读取C++源文件,如果发现有包含Q_OBJECT宏的类声明,就生成另外一个包含这些类的元对象代码的C++源文件。生成的源文件要么在类源文件里用#include包含,或者(更常见)与类的实现代码直接进行编译连接。

QObject::metaObject()返回类关联的meta-object对象。

QMetaObject::className()在运行时以字符串的形式返回类名,无需C++编译器提供运行时类别信息(RTTI)的支持。

QObject::inherits()返回一个对象是否是QObject继承树上一个类的实例。

QObject::tr()和QObject::trUtf8()提供国际化支持,将字符串翻译成指定的语言。

QObject::setProperty()和QObject::property()通过名称动态设置和获取属性。

QMetaObject::newInstance()构造类的一个新实例。
qobject_cast()动态转换QObject类的类型。qobject_cast()函数和标准C++的dynamic_cast()功能类似

    QObject *obj=new mywidget;
    QWidget  *wid=qobject_cast<QWidget *>(obj);
    wid->setObjectName("widget");
    mywidget *myw=qobject_cast<mywidget *>(wid);
属性

1.要声明一个属性,在继承QObject的类中使用Q_PROPERTY()宏


2.一个属性的行为就像一个类的数据成员,但它有通过元对象系统访问的附加功能。

声明属性需求
  • 如果MEMBER关键字没有被指定,则一个READ访问函数是必须的。它被用来读取属性值。理想的情况下,一个const函数用于此目的,并且它必须返回的是属性类型或const引用。比如:QWidget::focus是一个只读属性,通过READ函数QWidget::hasFocus()访问。

  • 一个WRITE访问函数是可选的,用于设置属性的值。它必须返回void并且只能接受一个参数,属性的类型是类型指针或引用,例如:QWidget::enabled具有WRITE函数QWidget::setEnabled()。只读属性不需要WRITE函数,例如:QWidget::focus没有WRITE函数。

  • 如果READ访问函数没有被指定,则MEMBER变量关联是必须的。这使得给定的成员变量可读和可写,而不需要创建READ和WRITE访问函数。如果需要控制变量访问,仍然可以使用READ和WRITE函数而不仅仅是MEMBER(但别同时使用)。

  • 一个RESET函数是可选的,用于将属性设置为上下文指定的默认值。例如:QWidget::cursor有READ和WRITE函数QWidget::cursor()和QWidget::setCursor(),同时也有一个RESET函数QWidget::unsetCursor(),因为没有可用的QWidget::setCursor()调用可以确定的将cursor属性重置为上下文默认的值。RESET函数必须返回void类型,并且不带任何参数。

  • 一个NOTIFY信号是可选的。如果定义了NOTIFY,则需要在类中指定一个已存在的信号,该信号在属性值发生改变时发射。与MEMBER变量相关的NOTIFY信号必须有零个或一个参数,而且必须与属性的类型相同。参数保存的是属性的新值。NOTIFY信号应该仅当属性值真正的发生变化时发射,以避免被QML重新评估。例如:当需要一个没有显式setter的MEMBER属性时,Qt会自动发射信号。

  • 一个REVISION数字是可选的。如果包含了该关键字,它定义了属性并且通知信号被特定版本的API使用(通常是QML);如果没有包含,它默认为0。

  • DESIGNABLE属性指定了该属性在GUI设计器(例如:Qt Designer)里的编辑器中是否可见。大多数的属性是DESIGNABLE (默认为true)。除了true或false,你还可以指定boolean成员函数。

  • SCRIPTABLE属性表明这个属性是否可以被一个脚本引擎操作(默认是true)。除了true或false,你还可以指定boolean成员函数。

  • STORED属性表明了该属性是否是独立存在的还是依赖于其它属性。它也表明在保存对象状态时,是否必须保存此属性的值。大多数属性是STORED(默认为true)。但是例如:QWidget::minmunWidth()的STROED为false,因为它的值从QWidget::minimumSize()(类型为QSize)中的width部分取得。

  • USER属性指定了属性是否被设计为用户可见和可编辑的。通常情况下,每一个类只有一个USER属性(默认为false)。例如: QAbstractButton::checked是(checkable)buttons的用户可修改属性。注意:QItemDelegate获取和设置widget的USER属性。

  • CONSTANT属性的出现表明属性是一个常量值。对于给定的object实例,常量属性的READ函数在每次被调用时必须返回相同的值。对于不同的object实例该常量值可能会不同。一个常量属性不能具有WRITE函数或NOYIFY信号。

  • FINAL属性的出现表明属性不能被派生类所重写。有些情况下,这可以用于效率优化,但不能被moc强制执行。必须注意不能覆盖一个FINAL属性。

  • 属性类型可以是QVariant支持的任何类型,或者是用户定义的类型。在这个例子中,类QDate被看作是一个用户定义的类型。

Q_PROPERTY(bool focus READ hasFocus)
Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
Q_PROPERTY(QCursor cursor READ cursor WRITE setCursor RESET unsetCursor)
   Q_PROPERTY(QColor color MEMBER m_color NOTIFY colorChanged)
    Q_PROPERTY(qreal spacing MEMBER m_spacing NOTIFY spacingChanged)
    Q_PROPERTY(QString text MEMBER m_text NOTIFY textChanged)
    ...
signals:
    void colorChanged();
    void spacingChanged();
    void textChanged(const QString &newText);

private:
    QColor  m_color;
    qreal   m_spacing;
    QString m_text;

一个属性可以使用常规函数QObject::property()和QObject::setProperty()进行读写,除了属性的名字,不用知道属性所在类的任何细节。

QPushButton *button = new QPushButton;
QObject *object = button;

button->setDown(true);
object->setProperty("down", true);
事件

在Qt中,事件就是对象,派生自QEvent抽象类

事件的运行过程

当一个事件发生时Qt会构造一个事件的对象,它识别事件类型,将事件发送给特定的对象,而后特定的对象将会返回特定的bool


事件机制
bool QCoreApplication::notify(QObject * receiver, QEvent * event) [virtual]
发送事件给接收者,接收者处理并返回状态.


事件处理陈程序
相当于一个虚函数,你也可以自己重写虚函数


事件过滤器
所谓事件过滤就是提前截获发往某个对象的所有消息,根据需要屏蔽掉某一些,或者对某些消息提前进行些处理,其他的事件处理将不会接收到该事件.

//eventfilter.cpp
#include "eventfilter.h"
#include <QEvent>
#include <QKeyEvent>

bool eventfilter::eventFilter(QObject *to, QEvent *event)//event filter(write number only)
{
    static QString digits = QString("1234567890");
    if(event->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*> (event);
        if( digits.indexOf(keyEvent->text()) != -1 )
        {
            return false;
        }
        return true;
    }
    return QObject::eventFilter(to, event);
}


//main.cpp
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    mywidget *myw=new mywidget;         //display widget
    eventfilter *eve=new eventfilter;   //evevt filter,it let textbroser write number only
    QTextEdit *textbrowser=new QTextEdit;
    textbrowser->installEventFilter(eve);//use filetr
    QVBoxLayout *layout=new QVBoxLayout(myw);
    layout->addWidget(textbrowser);
    myw->show();
    return a.exec();
}

发送事件
使用notify()函数直接给receiver发送事件。
postEvent(QObject* receiver, QEvent* event)
向事件队列中添加receiver和event。
简单说,sendEvent使用的是同步处理事件,postEvent使用的异步处理事件

QCoreApplication::sendEvent()
QCoreApplication::postEvent()

这里可以看到事件是如何处理的:
先送入Application的事件过滤器,看看是否在事件过滤器中处理
再查看receiver是否有此事件的过滤器
最后,将事件送入receiver的event接口。

常见的事件类型

QResizeEvent、QPaintEvent、QMouseEvent、QKeyEvent、QCloseEvent。

介绍

信号和插槽用于对象之间的通信。
在GUI编程中,当我们更改一个小部件时,我们经常需要通知另一个小部件。更一般地说,我们希望任何类型的对象能够彼此通信。例如,如果用户单击“ 关闭”按钮,我们可能希望调用窗口的close()函数。

运行机制

一个对象发出信号,另一个对象给出自己的插槽处理,其中slot的参数个数可少于sinal的参数个数,当然参数可以使用默认参数,as:change(int i=0);

#include <QObject>
class Counter : public QObject
{
    Q_OBJECT
public:
    Counter() { m_value = 0; }
    int value() const { return m_value; }
public slots:
void setValue(int value)
    {
        if (value != m_value)
         {
            m_value = value;
            //===========定义函数,发生将会发射sinal=======
            emit valueChanged(value);
         }
    }  
signals:
    void valueChanged(int newValue,int oldvalue);
private:
    int m_value;
};
Counter a, b;
    QObject::connect(&a, SIGNAL(valueChanged(int)),
                     &b, SLOT(setValue(int)));
    a.setValue(12);     // a.value() == 12, b.value() == 12
    b.setValue(48);     // a.value() == 12, b.value() == 48
   QObject::connect(&ac, SIGNAL(valueChanged(int,int)),&bc, SLOT(setValue(int)));//can use a`s arguments bigger b`s arguments
connect(buttonGroup, QOverload<int, bool>::of(&QButtonGroup::buttonToggled),
    [=](int id, bool checked){ /* ... */ });
//不用signal和slot的connect的写法,了解一下

QTimer


QTimer提供单词计时器和重复计时器
slots

void start([int msec])
void stop()

sinals

void timeout()

虚函数

virtual void timerEvent(QTimerEvent *e) override

class test : public QObject
{
    Q_OBJECT
public:
    test()
    {
        //intervals 0.5 seconds to say hello world
        QTimer *timer = new QTimer();
        connect(timer, &QTimer::timeout,[]{qDebug()<<"hello world";});
        timer->start(1000);
    }
};

//run
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    test t1;
    return a.exec();
}
   QTimer::singleShot(2000,[]{qDebug()<<"hello world";} );//
对象树销毁

当创建一个object对象时,如果使用了其他对象作为父对象,如果父对象被销毁,其被销毁.

构造和销毁的顺序

和c++一样,基类构造,子类构造,子类析构,基类析构,,但是在qt中,父类销毁了也就意味子类被销毁,so

int main()
{
    QPushButton quit("Quit");
    QWidget window;
    quit.setParent(&window);
    ...
}//have error
//如果动态创建就不会出现这些个问题,new,这里父窗口的析构函数将会最先被调用

int main()
{
    QWidget window;
    QPushButton quit("Quit", &window);
    ...
}//这里是正常的,其实吧这问题不了解也行,只要知道父销毁,子就被销毁就好

QWidgets

所有用户界面对象的基类。
Header: #include
qmake: QT += widgets

内容 函数名
窗口函数 show(),hide(),raise()//顶层,lower()//底层,close()
顶层窗口 windowModified, windowTitle, windowIcon, isActiveWindow, activateWindow(), minimized, showMinimized(), maximized, showMaximized(), fullScreen, showFullScreen(), showNormal().
窗口内容 update(), repaint(), scroll().//update()不会立即进行重绘事件,有一个事件循环,不会像repaint()那样发生闪烁
常规 pos, x(), y(), rect, size, width(), height(), move(), resize(), sizePolicy, sizeHint(), minimumSizeHint(), updateGeometry(), layout(), frameGeometry, geometry, childrenRect, childrenRegion, adjustSize(), mapFromGlobal(), mapToGlobal(), mapFromParent(), mapToParent(), maximumSize, minimumSize, sizeIncrement, baseSize, setFixedSize()
模式 visible, isVisibleTo(), enabled, isEnabledTo(), modal, isWindow(), mouseTracking, updatesEnabled, visibleRegion().
style style(), setStyle(), styleSheet, cursor, font, palette, backgroundRole(), setBackgroundRole(), fontInfo(), fontMetrics().
焦点 focus, focusPolicy, setFocus(), clearFocus(), setTabOrder(), setFocusProxy(), focusNextChild(), focusPreviousChild().
事件 event(), mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), keyPressEvent(), keyReleaseEvent(), focusInEvent(), focusOutEvent(), wheelEvent(), enterEvent(), leaveEvent(), paintEvent(), moveEvent(), resizeEvent(), closeEvent(), dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(), dropEvent(), childEvent(), showEvent(), hideEvent(), customEvent(). changeEvent()
系统函数 parentWidget(), window(), setParent(), winId(), find(), metric().
提示 setToolTip(), setWhatsThis()
slots
bool    close()
void    hide()
void    lower()
void    raise()
void    repaint()
void    setDisabled(bool disable)
void    setEnabled(bool)
void    setFocus()
void    setHidden(bool hidden)
void    setStyleSheet(const QString &styleSheet)
virtual void    setVisible(bool visible)
void    setWindowModified(bool)
void    setWindowTitle(const QString &)
void    show()
void    showFullScreen()
void    showMaximized()
void    showMinimized()
void    showNormal()
void    update()
protect function大部分可重写virtual
virtual void    actionEvent(QActionEvent *event)
virtual void    changeEvent(QEvent *event)
virtual void    closeEvent(QCloseEvent *event)
virtual void    contextMenuEvent(QContextMenuEvent *event)
void    create(WId window = 0, 
void    destroy(bool destroyWindow = true, bool destroySubWindows = true)
virtual void    dragEnterEvent(QDragEnterEvent *event)
virtual void    dragLeaveEvent(QDragLeaveEvent *event)
virtual void    dragMoveEvent(QDragMoveEvent *event)
virtual void    dropEvent(QDropEvent *event)
virtual void    enterEvent(QEvent *event)
virtual void    focusInEvent(QFocusEvent *event)
virtual bool    focusNextPrevChild(bool next)
virtual void    focusOutEvent(QFocusEvent *event)
bool    focusPreviousChild()
virtual void    hideEvent(QHideEvent *event)
virtual void    inputMethodEvent(QInputMethodEvent *event)
virtual void    keyPressEvent(QKeyEvent *event)
virtual void    keyReleaseEvent(QKeyEvent *event)
virtual void    leaveEvent(QEvent *event)
virtual void    mouseDoubleClickEvent(QMouseEvent *event)
virtual void    mouseMoveEvent(QMouseEvent *event)
virtual void    mousePressEvent(QMouseEvent *event)
virtual void    mouseReleaseEvent(QMouseEvent *event)
virtual void    moveEvent(QMoveEvent *event)
virtual bool    nativeEvent(const QByteArray &eventType, void *message, long *result)
virtual void    paintEvent(QPaintEvent *event)
virtual void    resizeEvent(QResizeEvent *event)
virtual void    showEvent(QShowEvent *event)
virtual void    tabletEvent(QTabletEvent *event)
virtual void    wheelEvent(QWheelEvent *event)

QDialog

对话窗口的基类
Header: #include
qmake: QT += widgets

public Types
enum    DialogCode { Accepted, Rejected }
Public Functions
QDialog(QWidget *parent = nullptr, Qt::WindowFlags f = ...)
virtual ~QDialog()
bool    isSizeGripEnabled() const
int result() const
void    setModal(bool modal)
void    setResult(int i)
void    setSizeGripEnabled(bool)
Public Slots
virtual void    accept()
virtual void    done(int r)
virtual int exec()
virtual void    open()
virtual void    reject()
Signals
void    accepted()
void    finished(int result)
void    rejected()

QWindow

Header: #include
qmake: QT += gui

QLabel

The QLabel widget provides a text or image display.

可以显示的文本
void    clear()
void    setMovie(QMovie *movie)
void    setNum(int num)
void    setNum(double num)
void    setPicture(const QPicture &picture)
void    setPixmap(const QPixmap &)
void    setText(const QString &)
属性的设置
函数 描述
setScaledContents(bool) 自动适应大小
void setIndent(int) 文本缩进几个像素单位
void setMargin(int) 边距
void setOpenExternalLinks(bool open) 可以打开链接
void setAlignment(Qt::Alignment) 对齐方式
void QLabel::setSelection(int start, int length) 选择
void setTextFormat(Qt::TextFormat) 文本格式
void setWordWrap(bool on) 自动显示全部

还有许多继承的东西,size,font,style等

判断
函数 描述
hasSelectedText() 判断文本是否被选择
hasScaledContents() 是否自动适应大小
值利用
函数 描述
int QLabel::selectionStart() const 选中文本的第一个char
事件
virtual void    changeEvent(QEvent *ev) override
virtual void    contextMenuEvent(QContextMenuEvent *ev) override
virtual bool    event(QEvent *e) override
virtual void    focusInEvent(QFocusEvent *ev) override
virtual bool    focusNextPrevChild(bool next) override
virtual void    focusOutEvent(QFocusEvent *ev) override
virtual void    keyPressEvent(QKeyEvent *ev) override
virtual void    mouseMoveEvent(QMouseEvent *ev) override
virtual void    mousePressEvent(QMouseEvent *ev) override
virtual void    mouseReleaseEvent(QMouseEvent *ev) override
virtual void    paintEvent(QPaintEvent *) override
例子
#include "mywidget.h"
#include<QTextEdit>
#include<QVBoxLayout>
#include<QString>
#include<QLabel>
#include<QPixmap>
#include<QMovie>
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);
    QLabel *mylabel=new QLabel;
    //settext()
    mylabel->setText("<p style=\"line-height:200%\">hello the world nihao<p>");//显示文本,行高2倍
    mylabel->setAlignment(Qt::AlignRight);    //右对齐
    mylabel->setWordWrap(true);               //自动显示越界文字
    mylabel->setLineWidth(30);                //行宽
    QString strHTML = QString("<html> \
                               <head> \
                               <style> \
                               font{color:red;} #f{font-size:18px; color: green;} \
                               </style> \
                               </head> \
                               <body>\
                               <font>%1</font><font id=\"f\">%2</font> \
                               <br/><br/> \
                               <img src=\":/image/wz2.jpg\" width=\"100\" height=\"100\"> \
                               </body> \
                               </html>").arg("I am a ").arg("Qter");
    mylabel->setText(strHTML);

    //setpixmap()
    QPixmap mypixmap(":/image/wz2.jpg");
    mylabel->setScaledContents(true);
    mylabel->setPixmap(mypixmap);

    //setmovie()
    QMovie *mymovie=new QMovie(":/image/c++猿");
    mylabel->setMovie(mymovie);
    mymovie->start();

    //openlinks
    mylabel->setText(QString("<a href = \"%1\">%2</a>").arg("www.baidu.com")
                     .arg(QStringLiteral("百度")));
    mylabel->setOpenExternalLinks(true);
    layout->addWidget(mylabel);
    this->show();
}

QLCDNumber

The QLCDNumber widget displays a number with LCD-like digits
Header:QLCDNumber
qmake: QT += widgets

属性设置
函数 描述
void setDigitCount(int numDigits) 长度
void setMode(QLCDNumber::Mode) 模式 hex dec oct bin
void setSegmentStyle(QLCDNumber::SegmentStyle) 外观 outline filled flat
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);

    QLCDNumber *mylcd=new QLCDNumber();
    mylcd->setDigitCount(20);
    mylcd->setMode(QLCDNumber::Dec);
    mylcd->setSegmentStyle(QLCDNumber::Flat);
    mylcd->setStyleSheet("color:red;font-size:50;");

    QTimer *ptimer=new QTimer;
    connect(ptimer,QTimer::timeout,[&mylcd]{
        mylcd->display(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz"));});
    layout->addWidget(mylcd);
    ptimer->start(1000);
    this->show();
}

QAbstractButton

自定义button

设置属性
函数 描述
void setCheckable(bool) 可选设置
void setChecked(bool) 选择
void setDown(bool) button按下
void setIcon(const QIcon &icon)
void setShortcut(const QKeySequence &key)
void setText(const QString &text)

void seticoSize()

判断
函数 描述
bool isCheckable() const 可选判断
bool isChecked() const 是否选中
bool isDown() const 是否按下
slots
void    animateClick(int msec = 100)
void    click()
void    setChecked(bool)
void    setIconSize(const QSize &size)
void    toggle()
sinals
void    clicked(bool checked = false)
void    pressed()
void    released()
void    toggled(bool checked)
小例子
mywidget::mywidget()
{
    loadstyle::setstyle(":/image/myqss.qss");
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);

    QAbstractButton *pbutton1=new  QPushButton("button1");

    pbutton1->setIcon(QIcon(":/image/wz2.jpg"));    //设置图标
    pbutton1->setIconSize(QSize(20,29));            //图标大小
    pbutton1->setCheckable(true);                   //设置可选中
    pbutton1->setChecked(true);                     //选中中
    pbutton1->setShortcut(Qt::Key_Home);
    connect(pbutton1,&QPushButton::clicked,[]{qDebug()<<"Enter....";});

    layout->addWidget(pbutton1);

    this->setFixedSize(300,300);
    this->show();
}
QButtonGroup

provides a container to organize groups of button widgets.
添加移除btn,查看选中的btn,找到想找的btn

函数 描述
void addButton(QAbstractButton *button, int id = -1) 添加button,且放置id
void removeButton(QAbstractButton *button) 移除
QAbstractButton *QButtonGroup::checkedButton() const Returns the button group’s checked button, or 0 if no buttons are checked.
int QButtonGroup::checkedId() const 返回选中的button的id,没有则-1
QAbstractButton * button(int id)const 返回你下面还要找的button
buttons() const 返回全部的zibutton
setExclusive(true) 属性,可以设置为互斥
sinals
void    buttonClicked(QAbstractButton *button)
void    buttonClicked(int id)
void    buttonPressed(QAbstractButton *button)
void    buttonPressed(int id)
void    buttonReleased(QAbstractButton *button)
void    buttonReleased(int id)
void    buttonToggled(QAbstractButton *button, bool checked)
void    buttonToggled(int id, bool checked)
/*
 * QButtonGroup have add remove but select one only
 *
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);

    pbtn_group=new QButtonGroup;
    QCheckBox *pradio_btn1=new QCheckBox("radio1");
    QCheckBox *pradio_btn2=new QCheckBox("radio2");

    QCheckBox *pradio_btn3=new QCheckBox("radio3");
    QCheckBox *pradio_btn4=new QCheckBox("radio4");
    pbtn_group->addButton(pradio_btn1,0);
    pbtn_group->addButton(pradio_btn2,1);
    pbtn_group->addButton(pradio_btn3,2);
    pbtn_group->addButton(pradio_btn4,3);
    pradio_btn1->setChecked(true);
    pradio_btn2->setChecked(true);
    pbtn_group->setExclusive(true);

//    connect(pbtn_group,SIGNAL(buttonClicked(int)),this,SLOT(reaction(int)));
    //use the another way to connect
    connect(pbtn_group, QOverload<int>::of(&QButtonGroup::buttonClicked),[&](int i){
        qDebug()<<"selct is :"<<i<<' '<<pbtn_group->checkedButton()->text();
        pbtn_group->button(2)->setChecked(true);
    });
    layout->addWidget(pradio_btn1);
    layout->addWidget(pradio_btn2);
    layout->addWidget(pradio_btn3);
    layout->addWidget(pradio_btn4);

    this->setFixedSize(300,300);
    this->show();
}


/*
 * 新技能..................
 * connect(buttonGroup, QOverload<int, bool>::of(&QButtonGroup::buttonToggled),
 * [=](int id, bool checked){ });
 */
 void mywidget::reaction(int i)
    {
     /*
      * 1.输出被选中的button的id和text
      * pbtn_group->checkedId();
      * pbtn_group->checkedButton()->text();
      * 2.改变选中的button,id=2
     */
        qDebug()<<"selct is :"<<i<<' '<<pbtn_group->checkedButton()->text();
        pbtn_group->button(2)->setChecked(true);
    }
QPushButton
设置
功能 描述
void setAutoDefault(bool)
void setDefault(bool) 默认的按钮
void setFlat(bool) 可以改变其中一些颜色属性
void setMenu(QMenu *menu) 菜单
slots

void showmenu()

事件
virtual bool    event(QEvent *e)
virtual void    focusInEvent(QFocusEvent *e)
virtual void    focusOutEvent(QFocusEvent *e)
virtual void    keyPressEvent(QKeyEvent *e)
virtual void    paintEvent(QPaintEvent *)
QToolButton

工具按钮,具备菜单等等

void setMenu(QMenu * menu) 
设置按钮的弹出菜单。和QPushButton用法类似,详见:Qt之QPushButton

void setPopupMode(ToolButtonPopupMode mode) 
设置弹出菜单的方式,默认情况下,设置为DelayedPopup(延迟弹出)。

枚举QToolButton::ToolButtonPopupModevoid setToolButtonStyle(Qt::ToolButtonStyle style) 
void setArrowType(Qt::ArrowType type) 
设置按钮是否显示一个箭头,而不是一个正常的图标。这将显示一个箭头作为QToolButton的图标。 
默认情况下,这个属性被设置为Qt::NoArrow
QRadioButton

单选框

QCheckBox

复选框,且可以开启三种状态,主要用来多选和三种状态,它有一个信号statechanged()
找它的状态可以isChecked(),checkstate()

功能设置
函数 描述
void setCheckState(Qt::CheckState state)
void setTristate(bool y = true) 开启三种选择状态

QLineEdit

行输入,作用进行输入,有最主要输入类型的控制,此外就是输入格式,即过滤一些东西

部件设置
函数 描述
void setAlignment(Qt::Alignment flag) 对齐方式
void setClearButtonEnabled(bool enable) 是否显示清除全部的按钮
void setCursorMoveStyle(Qt::CursorMoveStyle style) 鼠标形状
void setCursorPosition(int) 鼠标位置
void setDragEnabled(bool b) 允许拖动
void setEchoMode(QLineEdit::EchoMode) 输入类型,password等
void setFrame(bool)
void setInputMask(const QString &inputMask) 控制输入格式
void setMaxLength(int) 长度
void setModified(bool) 可修改
void setPlaceholderText(const QString &) 占位符,没输入时候显示的东西
void setReadOnly(bool) 只读
void setSelection(int start, int length) 设置选择范围
void setTextMargins(int left, int top, int right, int bottom) 设置边框
void setTextMargins(const QMargins &margins)
void setValidator(const QValidator *v) 控制可接受的输入
slots
void    clear()
void    copy() const
void    cut()
void    paste()
void    redo()
void    selectAll()
void    setText(const QString &)
void    undo()
signals
void    cursorPositionChanged(int oldPos, int newPos)
void    editingFinished()
void    returnPressed()
void    selectionChanged()
void    textChanged(const QString &text)
void    textEdited(const QString &text)
其他

1.mask

字符 含义
A ASCII字母字符是必须的,A-Z、a-z。
a ASCII字母字符是允许的,但不是必须的。
N ASCII字母字符是必须的,A-Z、a-z、0-9。
n ASCII字母字符是允许的,但不是必须的。
X 任何字符都是必须要的。
x 任何字符都是允许的,但不是必须要的。
9 ASCII数字是必须要的,0-9。
0 ASCII数字是允许的,但不是必须要的。
D ASCII数字是必须要的,1-9。
d ASCII数字是允许的,但不是必须要的 (1-9)。
# ASCII数字或加/减符号是允许的,但不是必须要的。
H 十六进制数据字符是必须要的,A-F、a-f、0-9。
h 十六进制数据字符是允许的,但不是必须要的。
B 二进制数据字符是必须要的,0-1。
b 二进制数据字符是允许的,但不是必须要的。
> 所有的字符字母都大写
< 所有的字符字母都小写
! 关闭大小写转换

| 使用 \ 去转义上述列出的字符。

例子
/*
 * QLineEdit
 * 输入类型的控制
 * setEchoMode(QLineEdit::Normal);                    
 * setPlaceholderText("Normal");                     
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);
    //echo mode
    QLineEdit *pnormal_line_edit = new QLineEdit(this);
    QLineEdit *pnoecho_line_edit = new QLineEdit(this);
    QLineEdit *ppassword_line_edit = new QLineEdit(this);
    QLineEdit *pdisplay_password_line_edit = new QLineEdit(this);

    pnormal_line_edit->setPlaceholderText("Normal");                        //提示框
    pnoecho_line_edit->setPlaceholderText("NoEcho");
    ppassword_line_edit->setPlaceholderText("Password");
    pdisplay_password_line_edit->setPlaceholderText("PasswordEchoOnEdit");

    pnormal_line_edit->setEchoMode(QLineEdit::Normal);                      //输入方式
    pnoecho_line_edit->setEchoMode(QLineEdit::NoEcho);
    ppassword_line_edit->setEchoMode(QLineEdit::Password);
    pdisplay_password_line_edit->setEchoMode(QLineEdit::PasswordEchoOnEdit);


    layout->addWidget(pnormal_line_edit);
    layout->addWidget(pnoecho_line_edit);
    layout->addWidget(ppassword_line_edit);
    layout->addWidget(pdisplay_password_line_edit);
    this->setFixedSize(300,300);
    this->show();
}
/*
 *AddAction()//添加行为
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);
    //echo mode
    QLineEdit *pline_edit = new QLineEdit(this);
    QAction *pleading_action=new QAction(this);
    pline_edit->setMaxLength(5);                                          //可输入五个字符
    pleading_action->setIcon(QIcon(":/image/wz2.jpg"));
    pline_edit->addAction(pleading_action,QLineEdit::LeadingPosition);
    pline_edit->setPlaceholderText("请输入搜索类容");                        //提示框
    QAction *pTrailingAction = pline_edit->addAction(QIcon(":/image/wz2.jpg"), QLineEdit::TrailingPosition);
    connect(pTrailingAction,QOverload<bool>::of(&QAction::triggered),[&pline_edit]{
        qDebug()<<"进行搜索的内容为:"<<pline_edit->text();});


    layout->addWidget(pline_edit);
    this->setFixedSize(300,300);
    this->show();
}
/*
 * 输入验证
 * QIntValidator整形类表达
 * QDoubleValidator小数类表达
 * QRegExp正则
 * QRegExpValidator正则类型数
 * 掩码
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);
    //input authentication
    QLineEdit *pline_edit = new QLineEdit(this);

    QIntValidator *int_validator=new QIntValidator(this);
    QDoubleValidator *double_validator=new QDoubleValidator(this);
    QRegExpValidator *regexp_validator=new QRegExpValidator(this);
    QRegExp regexp("[a-zA-Z0-9]+$");
    int_validator->setRange(1,99);
    double_validator->setRange(-200,200);
    double_validator->setDecimals(2);
    double_validator->setNotation(QDoubleValidator::StandardNotation);
    regexp_validator->setRegExp(regexp);

//    pline_edit->setValidator(int_validator);
    pline_edit->setValidator(double_validator);
//    pline_edit->setValidator(regexp_validator);

    QLineEdit *pline_edit2=new QLineEdit();
    pline_edit2->setInputMask("000.000.000.000;_");
//    pline_edit2->setInputMask("HH:HH:HH:HH:HH:HH;_");
//    pline_edit2->setInputMask("0000-00-00");
//    pline_edit2->setInputMask(">AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;#");

    layout->addWidget(pline_edit);
    layout->addWidget(pline_edit2);
    this->setFixedSize(300,300);
    this->show();
}

微调框

它可以调节值,具有范围,可以设置每次的波动大小,可以添加前缀和后缀

QSpinBox and QDoubleSpinBox
#设置
函数 描述
void setDisplayIntegerBase(int base) 显示的进制
void setMaximum(int max) 最大值
void setMinimum(int min) 最小值
void setPrefix(const QString &prefix) 前缀
void setRange(int minimum, int maximum) 范围
void setSingleStep(int val) 波动值
void setSuffix(const QString &suffix) 后缀 void setvalue()
setWrapping(true) 设置循环
virtual QString textFromValue(int value) 文本显示格式
#signal
void    valueChanged(double d)
void    valueChanged(const QString &text)
/*
 * 微调框的的属性
 * 前缀,后缀,步长,范围
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);
    // ...
    QSpinBox *pspinbox = new QSpinBox(this);
    pspinbox->setRange(0, 100);           // 范围
    pspinbox->setSingleStep(1);           // 步长
    pspinbox->setValue(10);               // 当前值
    pspinbox->setPrefix("下载进度 ");      // 前缀
    pspinbox->setSuffix(" %");            // 后缀
    pspinbox->setWrapping(true);          // 开启循环
    QTimer *ptimer=new QTimer(this);
    connect(ptimer,&QTimer::timeout,[&pspinbox]{
        int value=pspinbox->value()+1;
        pspinbox->setValue(value);
    });
    ptimer->start(1000);
    connect(pspinbox, QOverload<int>::of(&QSpinBox::valueChanged),
        [=](int value)
    {
        qDebug() << "Value : "  << value;
        qDebug() << "Text : "  << pspinbox->text();
    });
    //QDoubleSpinBox相似
    layout->addWidget(pspinbox);
    this->setFixedSize(300,300);
    this->show();
}
QSlider

水平滑动条的微调框,,步长,刻度

void    setTickInterval(int ti)//刻度间隔值
void    setTickPosition(QSlider::TickPosition position)//当前位置
#signals
valueChanged()  Emitted when the slider's value has changed. The tracking() determines whether this signal is emitted during user interaction.
sliderPressed() Emitted when the user starts to drag the slider.
sliderMoved()   Emitted when the user drags the slider.
sliderReleased()    Emitted when the user releases the slider.
// 滑动条
QSlider *pSlider = new QSlider(this);
pSlider->setOrientation(Qt::Horizontal);  // 水平方向
pSlider->setMinimum(nMin);  // 最小值
pSlider->setMaximum(nMax);  // 最大值
pSlider->setSingleStep(nSingleStep);  // 步长
/*
 * 滑动条的属性
 * 方向,范围,步长
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);
    // 滑动条
    QSlider *pslider = new QSlider(this);
    pslider->setOrientation(Qt::Horizontal);            // 水平方向
    pslider->setMinimum(0);                             // 最小值
    pslider->setMaximum(100);                           // 最大值
    pslider->setValue(0);
    pslider->setSingleStep(1);                          // 步长
    pslider->setTickInterval(100/5);                    //刻度间隔
    pslider->setTickPosition(QSlider::TicksAbove);      //刻度位置
    connect(pslider,QOverload<int>::of(&QSlider::valueChanged),[&pslider](int i){
       qDebug()<<i;
    });
     qDebug()<<pslider->value();
    layout->addWidget(pslider);
    this->setFixedSize(300,300);
    this->show();
}

进度条QProgressBar

文本,进度,那就提供了范围,文本的格式

功能设置
函数 功能
void setAlignment(Qt::Alignment alignment) 对齐方式
void setFormat(const QString &format) 文本格式,可重写
void setInvertedAppearance(bool invert) 反向进度读取
void setTextDirection(QProgressBar::Direction textDirection) 文字方向
void setTextVisible(bool visible) 文字可见
slots
void    reset()
void    setMaximum(int maximum)
void    setMinimum(int minimum)
void    setOrientation(Qt::Orientation)//水平还是垂直
void    setRange(int minimum, int maximum)
void    setValue(int value)
signals
void    valueChanged(int value)
/*
 * 进度条
 * 方向,范围,显示方式,水平,对齐
 * 
 * 程序在qt creator5.7运行,在第一个connect处发现申请内存异常
 * 加上一个语句就不出现运行时内存异常的错误
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);
    QTimer *ptimer= new QTimer(this);
    // 滑动条
    QProgressBar *ppro_bar = new QProgressBar(this);
    ppro_bar->setOrientation(Qt::Horizontal);    // 水平方向
    ppro_bar->setMinimum(0);                     // 最小值
    ppro_bar->setMaximum(100);                   // 最大值
    ppro_bar->setValue(50);                      // 当前进度
    ppro_bar->setInvertedAppearance(true);       // 反向读取
    ppro_bar->setTextDirection(QProgressBar::BottomToTop);//文字旋转了
                                                  //设置显示文本的格式

    qDebug()<<" ";//加上这个程序没出现运行时内存分配异常
    connect(ptimer,&QTimer::timeout,[&ppro_bar]{
         ppro_bar->setValue((ppro_bar->value())+10);
        if(ppro_bar->value()>=100)ppro_bar->setValue(0);
    });
    connect(ppro_bar,static_cast<void (QProgressBar::*)(int)>(&QProgressBar::valueChanged),[&ppro_bar]{
        ppro_bar->setFormat(QString("当前的值:%1%").
                            arg(QString::number(ppro_bar->value()-ppro_bar->minimum(),10)));
    });


    ptimer->start(1000);
    layout->addWidget(ppro_bar);

    this->setFixedSize(300,300);
    this->show();
}
QScrollArea

he QScrollArea class provides a scrolling view onto another widget.
可以滚动的区域

功能设置
函数 描述
void ignment(Qt::Alignment) 对齐方式
void setWidget(QWidget *widget) addwidget
void setWidgetResizable(bool resizable) 自动调整大小
/*
 * 滚动区域(失败的程序,随便看看代码就好)
 * setwidget
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);
    //滚动区域
    QScrollArea *pscroll_area=new QScrollArea(this);
    QLabel *plabel=new QLabel;
    QPixmap pixmap(":/image/wz2.jpg");
    pixmap.scaled(0.5,1);
    plabel->setPixmap(pixmap);
    pscroll_area->setWidget(plabel);        //addwidget
    pscroll_area->setAlignment(Qt::AlignCenter);
//    pscroll_area->widget()->resize(200,200);//手动调节大小
    pscroll_area->setWidgetResizable(true);  // 自动调整大小

    layout->addWidget(pscroll_area);

    this->setFixedSize(300,300);
    this->show();
}

QToolBox

The QToolBox class provides a column of tabbed widget items.
提供的是一个储存widget的列表
既然是储存,那就和数组差不多的原理,可以添加,插入,减少元素,同时可以快速找到元素,元素的数量,

具备的函数
函数 描述
int addItem(QWidget *widget, const QIcon &iconSet, const QString &text) 添加元素
int addItem(QWidget *w, const QString &text)
int count() const 元素的数量
int currentIndex() const 现在的index
QWidget * currentWidget() const 现在的widget
int indexOf(QWidget *widget) const 返回查找的widget的位置
int insertItem(int index, QWidget *widget, const QIcon &icon, const QString &text) 插入
int insertItem(int index, QWidget *widget, const QString &text)
bool isItemEnabled(int index) const
QIcon itemIcon(int index) const 返回icon
QString itemText(int index) const 返回text
QString itemToolTip(int index) const 返回提示
void removeItem(int index) 移除
void setItemEnabled(int index, bool enabled)
void setItemIcon(int index, const QIcon &icon) 设置icon
void setItemText(int index, const QString &text) 设置text
void setItemToolTip(int index, const QString &toolTip) 设置提示
void setCurrentIndex(int index) 设置现在的index,slot
signals
void    currentChanged(int index)
#include "mywidget.h"
#include "loadstyle.h"
#include<QVBoxLayout>
#include<QString>
#include<QPixmap>
#include<QLabel>
#include<QVBoxLayout>
#include<QDebug>
#include<QTimer>
#include<QHBoxLayout>
#include<QStringList>
#include<QScrollArea>
#include<QDoubleSpinBox>
#include<QToolbox>
#include<QGroupBox>
#include<QLabel>
/*
 * 三个分组,每个组5人
 *
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);         //整体的布局

    QToolBox *ptool_box=new QToolBox(this);
    QStringList groups;                                 //分组的名称
    groups<<"猴子1"<<"猴子2"<<"猴子3";
    for(int i=0;i<3;i++)
    {
        QGroupBox *pgroup=new QGroupBox(this);          //分组
        QVBoxLayout *pvbox_layout=new QVBoxLayout(pgroup);

        for(int j=0;j<5;j++)
        {
            pvbox_layout->addWidget(initperson(j));
        }

        ptool_box->addItem(pgroup,groups.at(i));

    }

    layout->addWidget(ptool_box);

    this->setFixedSize(400,500);
    this->show();
}

QWidget *mywidget::initperson(const int i)
{
    QWidget *person=new QWidget(this);
    QHBoxLayout *phbox_layout=new QHBoxLayout();
    QVBoxLayout *pvbox_layout=new QVBoxLayout();
    QLabel *phead=new QLabel(this);
    QLabel *pname=new QLabel(this);
    QLabel *psay=new QLabel(this);
    QPixmap ppixmap(":/image/hz"+QString::number(i+1,10)+".jpg");
    ppixmap=ppixmap.scaled(QSize(100,100),Qt::KeepAspectRatio);
    phead->setPixmap(ppixmap);
    pname->setText("孙悟空"+QString::number(i+1,10));
    psay->setText("我是第"+QString::number(i+1,10)+"个最好的孙悟空");
    pvbox_layout->addWidget(pname);
    pvbox_layout->addWidget(psay);
    phbox_layout->addWidget(phead);
    phbox_layout->addLayout(pvbox_layout);
    person->setLayout(phbox_layout);
    person->setFixedSize(300,100);
    return person;

}

qt 5

QSystemTrayIcon

系统托盘,属性主要是提示,是否可见

属性设置
函数 描述
void setContextMenu(QMenu *menu) 提示的菜单
void setIcon(const QIcon &icon) 图标
void setToolTip(const QString &tip) 提示的内容
slots
函数 描述
void hide() 隐藏
void setVisible(bool visible) 可见性
void show() 显示
void showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::Information, int millisecondsTimeoutHint = 10000) 显示的消息
void showMessage(const QString &title, const QString &message, const QIcon &icon, int millisecondsTimeoutHint = 10000)
signal
void    activated(QSystemTrayIcon::ActivationReason reason)
void    messageClicked()
枚举
**原因 描述
QSystemTrayIcon::Unknown 0 Unknown reason
QSystemTrayIcon::Context 1 The context menu for the system tray entry was requested
QSystemTrayIcon::DoubleClick 2 The system tray entry was double clicked.
QSystemTrayIcon::Trigger 3 The system tray entry was clicked
消息图标 Value Description
QSystemTrayIcon::NoIcon 0 No icon is shown.
QSystemTrayIcon::Information 1 An information icon is shown.
QSystemTrayIcon::Warning 2 A standard warning icon is shown.
QSystemTrayIcon::Critical 3 A critical warning icon is shown.
小例子

qt 5
qt 5

/*
 * 系统托盘
 * 可以显示小菜单,提示内容,信息
 * showmessage看用户的配置等,有时候根本不会出现
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);

    QMenu *pmenu=new QMenu;
    for(int i=0;i<5;i++)
    {
        QAction *Pacton=new QAction;
        Pacton->setIcon(QIcon(":/image/hz"+QString::number(i+1,10)+".jpg"));
        Pacton->setText("菜单"+QString::number(i+1,10));
        pmenu->addAction(Pacton);
    }
    QSystemTrayIcon *psystray=new QSystemTrayIcon(this);
    psystray->setContextMenu(pmenu);                        //set menu
    psystray->setIcon(QIcon(":/image/wz2.jpg"));            //set icon
    psystray->setToolTip("i`m systemtray ,don`t click me!");//set tip

    connect(psystray ,QOverload<QSystemTrayIcon::ActivationReason>::of(&QSystemTrayIcon::activated),
            [&psystray](QSystemTrayIcon::ActivationReason reason){
        switch(reason)
        {
            case QSystemTrayIcon::Trigger:
            {
                qDebug()<<"hello the world";
                psystray->showMessage("标题","内容",QSystemTrayIcon::Information);//有些系统根本不会出现,看配置和用户设置
                break;
            }
            case QSystemTrayIcon::Context:
            {
                break;
            }
            case QSystemTrayIcon::DoubleClick:
            {
                qDebug()<<"double click";
                break;
            }
        }
    });
    psystray->setVisible(true);
    psystray->show();


}

时间,不外乎就是获取时间,必要时转化一下时间显示格式.直接看例子吧

QDateEdit 和 QTimeEdit

QDateEdit
  • date:保存了部件的显示日期。
  • minimumDate:定义了用户可以设置的最小日期。
  • maximumDate:定义了用户可以设置的最大日期。
  • displayFormat:包含了一个字符串用于格式化日期。
QTimeEdit
  • time:保存了部件的显示时间。
  • minimumTime:定义了用户可以设- 置的最小时间。
  • maximumTime:定义了用户可以设置的最大时间。
  • displayFormat:包含了一个字符串用于格式化时间。
QDateTime
时间调整和范围设置
函数 描述
QDateTime addDays(qint64 ndays) const
QDateTime addMSecs(qint64 msecs) const
QDateTime addMonths(int nmonths) const
QDateTime addSecs(qint64 s) const
QDateTime addYears(int nyears) const
void setDate(const QDate &date)
void setTime(const QTime &time)
void setTimeSpec(Qt::TimeSpec spec) 区域时间
void setTimeZone(const QTimeZone &toZone) 时区
判断
函数 描述
bool isDaylightTime() const
bool isNull() const
bool isValid() const
格式转化
函数 描述
CFDateRef toCFDate() const
QDateTime toLocalTime() const
qint64 toMSecsSinceEpoch() const
NSDate * toNSDate() const
QDateTime toOffsetFromUtc(int offsetSeconds) const
qint64 toSecsSinceEpoch() const
QString toString(const QString &format) const
QString toString(Qt::DateFormat format = Qt::TextDate) const
QString toString(QStringView format) const
QDateTime toTimeSpec(Qt::TimeSpec spec) const
QDateTime toTimeZone(const QTimeZone &timeZone) const
QDateTime toUTC() const
格式控制
字符 表示
h the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
hh the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
H the hour without a leading zero (0 to 23, even with AM/PM display)
HH the hour with a leading zero (00 to 23, even with AM/PM display)
m the minute without a leading zero (0 to 59)
mm the minute with a leading zero (00 to 59)
s the whole second without a leading zero (0 to 59)
ss the whole second with a leading zero where applicable (00 to 59)
z the fractional part of the second, to go after a decimal point, without trailing zeroes (0 to 999). Thus “s.z” reports the seconds to full
zzz the fractional part of the second, to millisecond precision, including trailing zeroes where applicable (000 to 999).
AP or A use AM/PM display. A/AP will be replaced by either “AM” or “PM”.
ap or a use am/pm display. a/ap will be replaced by either “am” or “pm”.
t the timezone (for example “CEST”)

QDateTimeEdit

时间日期函数,可以设置显示格式,时间范围,调用日历

set
函数 描述
oid setCalendarPopup(bool enable) 弹出日历选择
void setCalendarWidget(QCalendarWidget *calendarWidget) 弹出的日历窗体
void setCurrentSection(QDateTimeEdit::Section section) 设置现在的session
void setCurrentSectionIndex(int index)
void setDateRange(const QDate &min, const QDate &max) data 范围
void setDateTimeRange(const QDateTime &min, const QDateTime &max) datetime 范围
void setDisplayFormat(const QString &format) 显示格式
void setMaximumDate(const QDate &max)
void setMaximumDateTime(const QDateTime &dt)
void setMaximumTime(const QTime &max)
void setMinimumDate(const QDate &min)
void setMinimumDateTime(const QDateTime &dt)
void setMinimumTime(const QTime &min)
void setSelectedSection(QDateTimeEdit::Section section) 设置当前的seeion
void setTimeRange(const QTime &min, const QTime &max)
void setTimeSpec(Qt::TimeSpec spec) 区域
slots
void    setDate(const QDate &date)
void    setDateTime(const QDateTime &dateTime)
void    setTime(const QTime &time)
signal
void    dateChanged(const QDate &date)
void    dateTimeChanged(const QDateTime &datetime)
void    timeChanged(const QTime &time)
/*
 * 时间日期函数
 * 时间的获取,输出的格式,转化类型给QString,日历的调用
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QVBoxLayout *layout=new QVBoxLayout(this);

    QDateTimeEdit *pdate_time_edit=new QDateTimeEdit(QDateTime::currentDateTime(),this);
    pdate_time_edit->setDateRange(QDate::currentDate().addDays(-365),QDate::currentDate().addDays(365));//设置范围
    pdate_time_edit->setTimeRange(QTime::currentTime().addMSecs(-10),QTime::currentTime().addMSecs(10));
    pdate_time_edit->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    pdate_time_edit->setCalendarPopup(true); //允许弹出日历
    layout->addWidget(pdate_time_edit);
    qDebug()<<"Date:"<<pdate_time_edit->date();
    qDebug()<<"date_time:"<<pdate_time_edit->dateTime();
    //signal
    connect(pdate_time_edit,QOverload<const QDate&>::of(&QDateTimeEdit::dateChanged),[&pdate_time_edit](QDate date){
        qDebug()<<"Date have change,now date is "<<date;
    });
    // 各部分对应的值
    QString strYear = pdate_time_edit->sectionText(QDateTimeEdit::YearSection);
    QString strMonth = pdate_time_edit->sectionText(QDateTimeEdit::MonthSection);
    QString strDay = pdate_time_edit->sectionText(QDateTimeEdit::DaySection);
    QString strHour = pdate_time_edit->sectionText(QDateTimeEdit::HourSection);
    QString strMinute = pdate_time_edit->sectionText(QDateTimeEdit::MinuteSection);
    QString strSecond = pdate_time_edit->sectionText(QDateTimeEdit::SecondSection);
    qDebug()<<strYear<<"年"<<strMonth<<"月"<<strDay<<"日\n"<<strHour<<":"<<strMinute<<":"<<strSecond;

    this->show();
}

布局管理器

布局管理器,有方向,间距,addwidget

描述
QBoxLayout 水平或垂直排列控件的基类
QButtonGroup 组织按钮的容器
QFormLayout 管理输入控件和其相关的标签
QGraphicsAnchor 表示在QGraphicsAnchorLayout中两个项目之间的锚
QGraphicsAnchorLayout 在图形视图中可以将锚连接到一起
QGridLayout 网格布局(多行多列)
QGroupBox 带标题的分组框
QHBoxLayout 水平排列控件
QLayout 几何管理器的基类
QLayoutItem 抽象的操作布局Item
QSizePolicy 描述水平和垂直大小调整的策略
QSpacerItem 布局中的空间隔
QStackedLayout 切换控件,同一时间只有一个控件可见
QStackedWidget 切换控件,同一时间只有一个控件可见
QVBoxLayout 垂直排列控件
QWidgetItem 表示一个控件的布局项
布局例子
QBoxLayout/QVBoxLayout/QHBoxlayout

拥有QHBoxLayout和QVBoxLayout

  • set
函数 描述
QBoxLayout(QBoxLayout::Direction dir, QWidget *parent = nullptr) 构造函数
virtual ~QBoxLayout() 析构函数
void addLayout(QLayout *layout, int stretch = 0) 添加
void addSpacerItem(QSpacerItem *spacerItem) 添加spaceitem
void addSpacing(int size) 间距
void addStretch(int stretch = 0) 可以让其居左或者居右或者居中,看例子
void addStrut(int size)
void addWidget(QWidget *widget, int stretch = 0, Qt::Alignment alignment = …) 对齐方式
QBoxLayout::Direction direction() const 方向
void insertItem(int index, QLayoutItem *item) 插入
void insertLayout(int index, QLayout *layout, int stretch = 0) 插入
void insertSpacerItem(int index, QSpacerItem *spacerItem)
void insertSpacing(int index, int size)
void insertStretch(int index, int stretch = 0)
void insertWidget(int index, QWidget *widget, int stretch = 0, Qt::Alignment alignment = …)
void setDirection(QBoxLayout::Direction direction) 设置方向
void setSpacing(int spacing) 设置空格
void setStretch(int index, int stretch) 设置长度
bool setStretchFactor(QWidget *widget, int stretch) 可以进行伸缩
bool setStretchFactor(QLayout *layout, int stretch)
int spacing() const 返回间距
int stretch(int index) const 返回长度

qt 5

/*
 * hbox and vbox 是box确定方向之后的产物,没啥特殊
 * box 属性有间距addspace,空白补齐addstrlen,以及方向direction
 * 他的函数也全部用来操作上面的属性
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");
    QHBoxLayout *layout=new QHBoxLayout(this);

    //垂直的布局
    QWidget *pvwidget=new QWidget(this);
    QBoxLayout *pvlayout=new QBoxLayout(QBoxLayout::BottomToTop,pvwidget);            //布局管理器
    for(int i=0;i<5;i++)
    {
        QPushButton *ppushbutton=new QPushButton("vertical"+QString::number(i+1,10));
        pvlayout->addWidget(ppushbutton);
    }

    //水平的布局
     QWidget *phwidget=new QWidget(this);
     QBoxLayout *phlayout=new QBoxLayout(QBoxLayout::RightToLeft,phwidget);            //布局管理器
     for(int i=0;i<5;i++)
     {

         phlayout->addStretch();//添加伸缩,此时会均分长度,但是在第一个控件前添加,会居右,最后一个控件后添加会居左
         QPushButton *ppushbutton=new QPushButton("horizontal"+QString::number(i+1,10));
         phlayout->addWidget(ppushbutton);
         if(i==2)phlayout->setStretchFactor(ppushbutton,2);                             //第三个可以进行拉伸
         ppushbutton->setFixedHeight(70);
         ppushbutton->setStyleSheet("font-size:30px;background:red;");
     }

     //间距space的设置
     pvlayout->setSpacing(0);
     phlayout->setSpacing(50);

     //其他
    pvlayout->setContentsMargins(50,50,50,50);                        //边距
    layout->addWidget(pvwidget);
    layout->addWidget(phwidget);
    this->show();
}

QGridLayout
函数 描述
void setColumnMinimumWidth(int column, int minSize) 列最小的宽度
void setColumnStretch(int column, int stretch) 可拉伸
void setHorizontalSpacing(int spacing) 水平间距
void setRowMinimumHeight(int row, int minSize) 行最小高度
void setRowStretch(int row, int stretch) 设置靠左靠右,或者平分,看qboxlayout的addstretch
void setSpacing(int spacing) 间距
void setVerticalSpacing(int spacing) 垂直间距
columnCount() 获取列数
rowCount() 获取行数

qt 5

/*
 * 头像 第0行,第0列开始,占3行1列
 * pLayout->addWidget(pImageLabel, 0, 0, 3, 1);
 * pLayout->setColumnMinimumWidth(1,100);          //特殊的列的宽度为100
 * pLayout->setRowMinimumHeight(3,10);             //特殊行的行高为10,
 * pLayout->setHorizontalSpacing(10);              //设置水平间距
 * pLayout->setVerticalSpacing(10);                //设置垂直间距
*/
mywidget::mywidget()
{
    setWindowTitle("my widget test");

    // 构建控件 头像、用户名、密码输入框等
    QLabel *pImageLabel = new QLabel(this);
    QLineEdit *pUserLineEdit = new QLineEdit(this);
    QLineEdit *pPasswordLineEdit = new QLineEdit(this);
    QCheckBox *pRememberCheckBox = new QCheckBox(this);
    QCheckBox *pAutoLoginCheckBox = new QCheckBox(this);
    QPushButton *pLoginButton = new QPushButton(this);
    QPushButton *pRegisterButton = new QPushButton(this);
    QPushButton *pForgotButton = new QPushButton(this);

    pLoginButton->setFixedHeight(30);
    pUserLineEdit->setFixedWidth(200);

    // 设置头像
    QPixmap pixmap(":/image/hz1.jpg");
    pImageLabel->setFixedSize(90, 90);
    pImageLabel->setPixmap(pixmap);
    pImageLabel->setScaledContents(true);

    // 设置文本
    pUserLineEdit->setPlaceholderText(QStringLiteral("QQ号码/手机/邮箱"));
    pPasswordLineEdit->setPlaceholderText(QStringLiteral("密码"));
    pPasswordLineEdit->setEchoMode(QLineEdit::Password);
    pRememberCheckBox->setText(QStringLiteral("记住密码"));
    pAutoLoginCheckBox->setText(QStringLiteral("自动登录"));
    pLoginButton->setText(QStringLiteral("登录"));
    pRegisterButton->setText(QStringLiteral("注册账号"));
    pForgotButton->setText(QStringLiteral("找回密码"));

    QGridLayout *pLayout = new QGridLayout(this);
    pLayout->setColumnMinimumWidth(1,100);          //特殊的列的宽度为100
    pLayout->setRowMinimumHeight(3,10);             //特殊行的行高为10,
    pLayout->setHorizontalSpacing(10);              //设置水平间距
    pLayout->setVerticalSpacing(10);                //设置垂直间距


    pLayout->addWidget(pImageLabel, 0, 0, 3, 1); // 头像 第0行,第0列开始,占3行1列
    pLayout->addWidget(pUserLineEdit, 0, 1,1,2);
    pLayout->addWidget(pPasswordLineEdit, 1, 1,1,2);
    pLayout->addWidget(pRegisterButton, 0, 3);
    pLayout->addWidget(pForgotButton, 1, 3);
    pLayout->addWidget(pRememberCheckBox, 2, 1, 1, 1, Qt::AlignLeft | Qt::AlignVCenter);
    pLayout->addWidget(pAutoLoginCheckBox, 2, 2, 1, 1, Qt::AlignRight | Qt::AlignVCenter);
    pLayout->addWidget(pLoginButton, 3, 1,1,2);
    pLayout->setContentsMargins(10, 10, 10, 10);
    setLayout(pLayout);
    this->show();
}
表单布局QFormLayout

一般不常用,需要是看文档

qt 5

mywidget::mywidget()
{
    QLineEdit *nameLineEdit=new QLineEdit(this);
    QLineEdit *emailLineEdit=new  QLineEdit(this);
    QSpinBox *ageSpinBox=new QSpinBox(this);
    QFormLayout *formLayout = new QFormLayout;
    formLayout->addRow(tr("&Name:"), nameLineEdit);
    formLayout->addRow(tr("&Email:"), emailLineEdit);
    formLayout->addRow(tr("&Age:"), ageSpinBox);
    setLayout(formLayout);
    this->show();
}
可以进行页面切换的布局QStackedLayout

找到现在的位置,可以到达想去的位置
QStackedWidget类似

函数 描述
int addWidget(QWidget *widget) 添加widget
int currentIndex() const 返回位置
QWidget * currentWidget() const 返回位置
int insertWidget(int index, QWidget *widget) 插入wedget
void setStackingMode(QStackedLayout::StackingMode stackingMode)
void setCurrentIndex(int index) 到达想去的wibget
void setCurrentWidget(QWidget *widget) 到达想去的位置

signal

void    currentChanged(int index)
void    widgetRemoved(int index)

qt 5

/*
 * QStackedLayout
 * addwidget添加widget
 * currentIndex()返回现在的位置
 * sercurrentindex()设置现在的位置
*/
mywidget::mywidget()
{
    //主要的布局
    setWindowTitle("widget test");
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QLabel *now_index=new QLabel(this);
    QPushButton *next_widget=new QPushButton("下一页");
    QPushButton *prior_widget=new QPushButton("上一页");
    QLineEdit *to_widget=new QLineEdit;
    to_widget->setPlaceholderText("跳转到页数");
    QPushButton *summit=new QPushButton("跳转");
    QHBoxLayout *menu_widget_layout=new QHBoxLayout;
    menu_widget_layout->addWidget(prior_widget);
    menu_widget_layout->addWidget(next_widget);
    menu_widget_layout->addWidget(to_widget);
    menu_widget_layout->addWidget(summit);
    menu_widget_layout->addWidget(now_index);


    //可以跳转页面的layout
    QStackedLayout *stack_layout = new QStackedLayout;
    QWidget *widget_1 = new QWidget;
    QWidget *widget_2 = new QWidget;
    QWidget *widget_3 = new QWidget;

    stack_layout->addWidget(widget_1);
    stack_layout->addWidget(widget_2);
    stack_layout->addWidget(widget_3);

    mainLayout->addLayout(menu_widget_layout);
    mainLayout->addLayout(stack_layout);
    now_index->setText("第"+QString::number(stack_layout->currentIndex()+1,10)
                       +"页,共"+QString::number(stack_layout->count(),10) +"页");

    //信号和槽,实现上一页,下一页,跳转功能
    connect(summit,QOverload<bool>::of(&QPushButton::clicked),[stack_layout,to_widget]{
         if(stack_layout->currentIndex() >=0 && stack_layout->currentIndex()<=stack_layout->count()-1)
        stack_layout->setCurrentIndex(to_widget->text().toInt()-1);

    });
    connect(prior_widget,QOverload<bool>::of(&QPushButton::clicked),[stack_layout]{
        if(stack_layout->currentIndex() >=0 && stack_layout->currentIndex()<=stack_layout->count()-1)
        stack_layout->setCurrentIndex(stack_layout->currentIndex()-1);
    });
    connect(next_widget,QOverload<bool>::of(&QPushButton::clicked),[stack_layout]{
        if(stack_layout->currentIndex() >=0 && stack_layout->currentIndex()<=stack_layout->count()-1)
        stack_layout->setCurrentIndex(stack_layout->currentIndex()+1);
    });
    connect(stack_layout,QOverload<int>::of(&QStackedLayout::currentChanged),[now_index,stack_layout]{
        now_index->setText("第"+QString::number(stack_layout->currentIndex()+1,10)
                           +"页,共"+QString::number(stack_layout->count(),10) +"页");
    });
    setLayout(mainLayout);
    this->show();
}
QSpacerItem提供一个空白区域
pHLayout->addSpacerItem(new QSpacerItem(20, 20));

qt_文件管理

QDir,QFile

QDir

获取路径和进入文件夹,删除文件,文件夹

枚举

enum Filter { Dirs, AllDirs, Files, Drives, …, CaseSensitive }
flags Filters
enum SortFlag { Name, Time, Size, Type, …, LocaleAware }
flags SortFlags

函数 描述
QString absoluteFilePath(const QString &fileName) const 返回文件的绝对位置+文件名,不检查是否存在,exist去检查就好
QString absolutePath() const QDir的绝对路径
QString dirName() const 返回dir路径名
QString filePath(const QString &fileName) const 返回路径名
QString path() const 路径
QString relativeFilePath(const QString &fileName) const 返回路径名
int count()const 返回的是该目录下文件夹和文件的数量+./+../
QFileInfoList entryInfoList(const QStringList &nameFilters, QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const 每一个文件或者文件的对象列表
QStringList entryList(const QStringList &nameFilters, QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const 文件和目录的名称列表
QDir::SortFlags sorting() const 返回排序的规律
QDir home()
QString homePath()
QDir root()
QString rootPath()
QDir temp()
QString tempPath()
判断
函数 描述
bool isAbsolute() const 绝对位置
bool isEmpty(QDir::Filters filters = Filters(AllEntries NoDotAndDotDot)) const
bool isReadable() const 可读
bool isRelative() const 相对位置
bool isRoot() const 根目录
bool exists(const QString &name) const
bool exists() const 存在
操作
函数 描述
bool cd(const QString &dirName)
bool cdUp()
bool mkdir(const QString &dirName) const 创建目录
bool mkpath(const QString &dirPath) const 创建一长串的目录
void refresh() const 刷新
bool remove(const QString &fileName) 删除文件
bool rename(const QString &oldName, const QString &newName) 重命名
bool rmdir(const QString &dirName) const 删除目录
bool rmpath(const QString &dirPath) const 删除多个目录
void setSorting(QDir::SortFlags sort) 设置排序
void setFilter(QDir::Filters filters) 设置过滤器
void setNameFilters(const QStringList &nameFilters)
void setPath(const QString &path) 设置path
/*
 * get information
 * absoluteFilePath("hz1.jpg")返回文件的绝对路径的名字
 * absolutePath()返回dir绝对路径
 * dirName()返回dir的名字
 * count()返回文件及./ ../的数量
 *
 * dispose dir
 * cd   cdUp    mkdir    mkpath
 *
*/


FileIo::FileIo(QWidget *parent)
    : QWidget(parent)
{

    setWindowTitle("file system");

    QDir file_dir("E:/qttest/testqrc");
    //获取信息
    if(file_dir.exists("hz1.jpg"))
        qDebug()<<file_dir.absoluteFilePath("hz1.jpg");//假如存在就会输出E:/qttest/hz10.jpg,但是这文件的
                                                       //地址是E:/qttest/testqrc/hz10.jpg,慎用
//    qDebug()<<file_dir.absolutePath();                 //绝对路径名
//    qDebug()<<file_dir.dirName();                      //路径名
//    qDebug()<<file_dir.count();                        //文件数量
    allFile("E:/newfile1");                    //文件的属性
    rmAll("E:/newfile1");
    //操作
    //file_dir.mkpath("E:/newfile1/newfile2/newfile3");  //可以创建多个新文件夹
    //file_dir.mkdir("E:/1");                            //创建一个
    //file_dir.rmpath("E:/newfile1/newfile2/newfile3");  //删除空文件夹多个
    //file_dir.rmdir("E:/1");
    //file_dir.setPath("E:/newfile1");




}

QFileInfo

提供一系列文件信息,前缀,后缀,大小,创建时间…..相当于文件的属性,详细信息

函数 描述
QDir absoluteDir() const 绝对位置的Dir
QDir dir() const 返回dir
QString absoluteFilePath() const 路径名
QString path() const 路径名
QString absolutePath() const
QString baseName() const 名称第一部分
QString suffix() const 文件后缀
qint64 size() const 大小
QDateTime birthTime() const 创建时间
QDateTime lastModified() const 最后修改时间
QDateTime lastRead() const 最后访问时间
QDateTime metadataChangeTime() const 比如权限被修改时间
bool permission(QFile::Permissions permissions) const 是否具有文件权限
QFile::Permissions permissions() const 文件的权限
QString owner() const 文件属于谁
uint ownerId() const 文件主的id
QString bundleName() const 包名称
bool caching() const 是否为缓存
QString canonicalFilePath() const 链接路径
QString canonicalPath() const 链接路径
QString completeBaseName() const 文件名称,去掉后缀
QString completeSuffix() const 文件后缀,去掉第一部分也就是文件名称
bool exists() const 判端是否存在
QString fileName() const 文件的名称
QString filePath() const 文件的路径
QString group() const 文件的组名称,unix里面
uint groupId() const 文件的组的id
bool isAbsolute() const 是否为绝对路径
bool isBundle() const 是否为包
bool isExecutable() const 可执行
bool isReadable() const 可读
bool isWritable() const 可写
bool isFile() const 文件,而不是目录
bool isDir() const 是否为目录
bool isHidden() const 隐藏文件
bool isNativePath() const 本地文件,而不是资源文件下的东西
bool isRelative() const 相对文件,在资源文件下,或者默认目录下的
bool isRoot() const
bool isSymLink() const 是否链接文件
QString symLinkTarget() const 链接文件的名字
void refresh() 刷新文件的信息
void setCaching(bool enable) 设为缓存
void setFile(const QString &file) 设置文件
void setFile(const QFile &file)
void setFile(const QDir &dir, const QString &file)

qt 5

void readAllFile(const QString & path)
{
    QTextStream cout(stdout);
    cout.setFieldWidth(20);
    cout<<endl;
    cout.setFieldAlignment(QTextStream::AlignLeft);
    QDir dir(path);
    if (!dir.exists())
        return ;
    QFileInfoList list = dir.entryInfoList(QDir::Files|QDir::Dirs,QDir::Time);
    int i = 0;
    do{
        QFileInfo fileInfo = list.at(i);
        if(fileInfo.fileName()=="." | fileInfo.fileName()=="..")
        {
            i++;
            continue;
        }
        bool bisDir = fileInfo.isDir();
        if(bisDir)
        {
            readAllFile(fileInfo.filePath());
        }
        else
        {
             cout<<fileInfo.path()<<fileInfo.fileName()<<fileInfo.created().toString
                   ("yyyy-MM-d h:m:s")<<fileInfo.size()/(1024.0)<<"\n";
        }
        i++;
    }while(i < list.size());
}

void rmAllFile(const QString &path)
{
    QDir dir(path);
    if (!dir.exists())
        return ;
    QFileInfoList list = dir.entryInfoList(QDir::Files|QDir::Dirs,QDir::Time);
    int i = 0;
    do{
        QFileInfo fileInfo = list.at(i);
        if(fileInfo.fileName()=="." | fileInfo.fileName()=="..")
        {
            i++;
            continue;
        }
        bool bisDir = fileInfo.isDir();
        if(bisDir)
        {
            rmAllFile(fileInfo.filePath());
        }
        else
        {
             dir.remove(fileInfo.absoluteFilePath());
        }
        i++;
    }while(i < list.size());
    dir.rmpath(path);
}

QFile

函数 描述
bool copy(const QString &newName) 赋值
bool link(const QString &linkName) 链接
bool remove() 删除
bool open(FILE *fh, QIODevice::OpenMode mode, QFileDevice::FileHandleFlags handleFlags = DontCloseHandle) 打开
void setFileName(const QString &name) 设置名字
bool rename(const QString &oldName, const QString &newName) 重命名
   QFile file("in.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        process_line(line);
    }
/*
 * Qfile取得一个文件的地址,然后对文件进行操作
 * rename copy  写入 读出
*/

FileIo::FileIo(QWidget *parent)
    : QWidget(parent)
{

    setWindowTitle("file system");
    QFile file("E:/1.txt");
    QTextStream out(&file);
     QTextStream cout(stdout);
    file.open(QFile::ReadWrite|QFile::Text);
    out<<"myname is zyldcsdfcsdfcsdg"<<endl;
    cout<<file.readAll();
    file.close();

}

QTextStream

text的流,相同的data流也存在

函数 描述
bool atEnd() const 流指针是否在末尾
qint64 pos() const 流指针位置
QString read(qint64 maxlen) 读文件
QString readAll() 读文件
QString readLine(qint64 maxlen = 0) 读文件
void reset() 充值流默认设置
void resetStatus() 重置流状态
bool seek(qint64 pos) 跳转
void setCodec(QTextCodec *codec) 设置编码格式
void setCodec(const char *codecName)
void setDevice(QIODevice *device) 设置设备
void setFieldAlignment(QTextStream::FieldAlignment mode) 对齐方式
void setFieldWidth(int width) 宽度
void setGenerateByteOrderMark(bool generate) 会插入bom标记
void setIntegerBase(int base) 进制设置
void setNumberFlags(QTextStream::NumberFlags flags) 设置标志
void setPadChar(QChar ch) 空白填充
void setRealNumberPrecision(int precision) 设置小数的位数
void setStatus(QTextStream::Status status) 流状态

status:

函数 描述
QTextStream::Ok 0 The text stream is operating normally.
QTextStream::ReadPastEnd 1 The text stream has read past the end of the data in the underlying device.
QTextStream::ReadCorruptData 2 The text stream has read corrupt data.
QTextStream::WriteFailed 3 The text stream cannot write to the underlying device.
/*
 * QtextStream相当于c++的iostram
 * pos位置 seek跳转  atend是否末尾
 *
*/

FileIo::FileIo(QWidget *parent)
    : QWidget(parent)
{

    setWindowTitle("file system");
    QFile file("E:/1.txt");
    QTextStream out(&file);
    QTextStream cout(stdout);
    file.open(QFile::ReadWrite|QFile::Text);
    if(out.atEnd())cout<<"this is end\n";
    cout<<"pos:"<<out.pos()<<endl;      //位置
    out.setCodec("utf-8");              //编码
    out.seek(0);                        //跳转位置
    cout.setIntegerBase(10);             //输出控制,二进制
    cout.setRealNumberPrecision(2);     //小数的位数是2,最多是2
    cout<<out.readAll()<<endl;
    cout<<out.device()<<endl;
    cout<<bin<<5023.5/1024.0;

    file.close();

}

qt_文件运用,调用桌面

QFileSystemWatcher

函数 描述
bool addPath(const QString &path) 添加一个path
QStringList addPaths(const QStringList &paths) 添加一个路径
QStringList directories() const 监控目录的顺序
bool removePath(const QString &path) 删除
QStringList removePaths(const QStringList &paths)

sinals:

函数 描述
void directoryChanged(const QString &path) 目录改变
void fileChanged(const QString &path) 文件改变
/*
 * 文件监视QFileSystemWatcher
 * addpath  removepath
 * directoryChanged     fileChanged
 * 监视整个路径,那就可以前后做比较,找出哪个文件发生了什么,最主要是qset的魅力
 *
 *
*/

FileIo::FileIo(QWidget *parent)
    : QWidget(parent)
{

    QTextStream cout(stdout);
    setWindowTitle("file system");
    QFileSystemWatcher *pfile_watch=new QFileSystemWatcher;
    path_str="E:/";
    QDir dir(path_str);
    pfile_watch->addPath(path_str);
    currentDirSet=QSet<QString>::fromList(dir.entryList(QDir::Dirs|QDir::Files));
    connect(pfile_watch,SIGNAL(directoryChanged(QString)),this,SLOT(direchange(QString)));



}
void FileIo::direchange(QString path)
{
   QTextStream cout(stdout);
   QDir dir(path_str);
   QSet<QString> newDirSet=QSet<QString>::fromList(dir.entryList(QDir::Dirs|QDir::Files));

   QStringList newFile = (newDirSet - currentDirSet).toList();    // 添加了文件
   QStringList deleteFile = (currentDirSet - newDirSet).toList(); // 文件已被移除
   currentDirSet=newDirSet;                                        //更新储存的目录内容
    if (!newFile.isEmpty() && !deleteFile.isEmpty())
       {
           // 文件/目录重命名
           if ((newFile.count() == 1) && (deleteFile.count() == 1))
           {
               cout << QString("File Renamed from %1 to %2").arg(deleteFile.first()).arg(newFile.first())<<endl;
           }
       }
    else
       {
           // 添加新文件/目录至Dir
           if (!newFile.isEmpty())
           {
               cout << "New Files/Dirs added: " ;

               foreach (QString file, newFile)
               {
                   // 处理操作每个新文件....
                   cout<<file<<endl;
               }
           }

           // 从Dir中删除文件/目录
           if (!deleteFile.isEmpty())
           {
              cout << "Files/Dirs deleted: " ;

               foreach(QString file, deleteFile)
               {
                   // 处理操作每个被删除的文件....
                   cout<<file<<endl;
               }
           }
       }
}
//源码见上传资源_文件目录监视https://download.csdn.net/download/qq_33564134/10618873

QDesktopServices

函数 描述
bool openUrl(const QUrl &url) 打开一个url
void setUrlHandler(const QString &scheme, QObject *receiver, const char *method) 定制.但是不会…
void unsetUrlHandler(const QString &scheme)

QFileIconProvider

enum QFileIconProvider::IconType

Constant Value
QFileIconProvider::Computer 0
QFileIconProvider::Desktop 1
QFileIconProvider::Trashcan 2
QFileIconProvider::Network 3
QFileIconProvider::Drive 4
QFileIconProvider::Folder 5
QFileIconProvider::File 6

qt 5

/*
 * 两个途径获取文件的icon
 * pfileico->icon((QFileIconProvider::IconType)1)
 * pfileico->icon(info)
*/

FileIo::FileIo(QWidget *parent)
    : QWidget(parent)
{

    setWindowTitle("file system");
    QFileInfo info("E:/1.txt");
    QListWidgetItem *pItem = new QListWidgetItem;
    QListWidget  *list_widget=new QListWidget(this);
    QFileIconProvider *pfileico=new QFileIconProvider;
    list_widget->setFixedSize(400,400);
    list_widget->setIconSize(QSize(200,200));
    pItem->setIcon(pfileico->icon((QFileIconProvider::IconType)1));
    pItem->setText("电脑");
    list_widget->addItem(pItem);
    pItem=new QListWidgetItem;
    pItem->setIcon(pfileico->icon(info));
    pItem->setText("文本文件");
    list_widget->addItem(pItem);

}

QCryptographicHash加密

QByteArray byteArray;
byteArray.append("password");
QByteArray hash = QCryptographicHash::hash(byteArray, QCryptographicHash::Md5);
QString strMD5 = hash.toHex();