c++风格
头文件作用域类函数study for googleelse study命名规则注释格式pro文件详解
TAMPLATEHEADERSSOURCESFORMS / INTERFACESLEXSOURCESYACCSOURCESTARGETDESTDIRDEFINESINCLUDEPATHDEPENDPATHVPATHDEF_FILEC_FILERES_FILECONFIG变量元对象系统
属性
声明属性需求事件
事件的运行过程常见的事件类型介绍
运行机制QTimer
slotssinals虚函数对象树销毁构造和销毁的顺序QWidgets
slotsprotect function大部分可重写virtualQDialog
public TypesPublic FunctionsPublic SlotsSignalsQWindowQLabel
可以显示的文本属性的设置判断值利用事件例子QLCDNumber
属性设置QAbstractButton
设置属性判断slotssinals小例子QButtonGroupsinalsQPushButton
设置slots事件QToolButton
QRadioButtonQCheckBox
功能设置QLineEdit
部件设置slotssignals其他例子微调框
QSpinBox and QDoubleSpinBox#设置#signalQSlider#signals进度条QProgressBar
功能设置slotssignalsQScrollArea功能设置QToolBox
具备的函数signalsQSystemTrayIcon
属性设置slotssignal枚举小例子QDateEdit 和 QTimeEdit
QDateEditQTimeEditQDateTime
时间调整和范围设置判断格式转化格式控制QDateTimeEdit
setslotssignal布局管理器
布局例子
QBoxLayout/QVBoxLayout/QHBoxlayoutQGridLayout表单布局QFormLayout可以进行页面切换的布局QStackedLayoutQSpacerItem提供一个空白区域qt_文件管理
QDir
获取路径和进入文件夹,删除文件,文件夹判断操作QFileInfoQFileQTextStreamqt_文件运用,调用桌面
QFileSystemWatcherQDesktopServicesQFileIconProviderQCryptographicHash加密
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保护
...
尽量避免前置声明
waht is 前置声明?
class Date
{
private:
int year, month, day;
};
class Date;
class Task1
{
public:
Date getData();
};
#include "Date.h"
class Task2
{
public:
Date getData();
};
慎用内联函数
在函数很短,可以内联,但是得保证此函数很少被调用
include的路径和顺序
#include <zylg.h>
#include "zylg.h"
作用域
#ifndef MYTEST_H
#define MYTEST_H
#include<iostream>
const int i=
5;
namespace zylg
{
void s();
namespace
{
void s1(){
std::
cout<<
"my is inline namespace function,as in static area,\n other file don`t use me\n";}
}
};
#endif
#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(
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.函数参数顺序 函数的参数顺序为: 输入参数在先, 后跟输出参数.
编写简短函数,我们倾向于编写简短, 凝练的函数.
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 中被认可的库.
命名规则
函数命名, 变量命名, 文件命名要有描述性; 少用缩写.
注释
使用 // 或 /* */, 统一就好.
在每一个文件开头加入版权公告.描述了该文件的内容
每个类的定义都要附带一份注释, 描述类的功能和用法, 除非它的功能相当明显.
通常变量名本身足以很好说明变量用途. 某些情况下, 也需要额外的注释说明.
格式
pro文件详解
TAMPLATE
描述为建立目标文件而采用的模板,即生成何种makefile文件 a.app(应用程序) b.lib(库文件) c.subdirs(子工程) d.vcapp(仅用于windows的应用程序) e.vclib
所有头文件列表
SOURCES
源文件列表
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] 发送事件给接收者,接收者处理并返回状态.
事件处理陈程序 相当于一个虚函数,你也可以自己重写虚函数
事件过滤器 所谓事件过滤就是提前截获发往某个对象的所有消息,根据需要屏蔽掉某一些,或者对某些消息提前进行些处理,其他的事件处理将不会接收到该事件.
#include "eventfilter.h"
#include <QEvent>
#include <QKeyEvent>
bool eventfilter::eventFilter(QObject *to, QEvent *event)
{
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);
}
int main(
int argc,
char *argv[])
{
QApplication a(argc, argv);
mywidget *myw=
new mywidget;
eventfilter *eve=
new eventfilter;
QTextEdit *textbrowser=
new QTextEdit;
textbrowser->installEventFilter(eve);
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;
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);
b.setValue(
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()
{
QTimer *timer =
new QTimer();
connect(timer, &QTimer::timeout,[]{qDebug()<<
"hello world";});
timer->start(
1000);
}
};
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);
...
}//这里是正常的,其实吧这问题不了解也行,只要知道父销毁,子就被销毁就好
所有用户界面对象的基类。 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().stylestyle(), 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;
mylabel
->setText(
"<p style=\"line-height:200%\">hello the world nihao<p>");
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);
QPixmap mypixmap(
":/image/wz2.jpg");
mylabel
->setScaledContents(
true);
mylabel
->setPixmap(mypixmap);
QMovie
*mymovie
=new QMovie(
":/image/c++猿");
mylabel
->setMovie(mymovie);
mymovie
->start();
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 binvoid 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();
}
自定义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();
}
provides a container to organize groups of button widgets. 添加移除btn,查看选中的btn,找到想找的btn
函数描述
void addButton(QAbstractButton *button, int id = -1)添加button,且放置idvoid removeButton(QAbstractButton *button)移除QAbstractButton *QButtonGroup::checkedButton() constReturns the button group’s checked button, or 0 if no buttons are checked.int QButtonGroup::checkedId() const返回选中的button的id,没有则-1QAbstractButton * button(int id)const返回你下面还要找的buttonbuttons() const返回全部的zibuttonsetExclusive(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);
}
设置
功能描述
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 *)
工具按钮,具备菜单等等
void setMenu(QMenu
* menu)
设置按钮的弹出菜单。和QPushButton用法类似,详见:Qt之QPushButton
void setPopupMode(ToolButtonPopupMode mode)
设置弹出菜单的方式,默认情况下,设置为DelayedPopup(延迟弹出)。
枚举QToolButton
::ToolButtonPopupMode:
void setToolButtonStyle(Qt
::ToolButtonStyle style)
void setArrowType(Qt
::ArrowType type)
设置按钮是否显示一个箭头,而不是一个正常的图标。这将显示一个箭头作为QToolButton的图标。
默认情况下,这个属性被设置为Qt
::NoArrow。
单选框
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
字符含义
AASCII字母字符是必须的,A-Z、a-z。aASCII字母字符是允许的,但不是必须的。NASCII字母字符是必须的,A-Z、a-z、0-9。nASCII字母字符是允许的,但不是必须的。X任何字符都是必须要的。x任何字符都是允许的,但不是必须要的。9ASCII数字是必须要的,0-9。0ASCII数字是允许的,但不是必须要的。DASCII数字是必须要的,1-9。dASCII数字是允许的,但不是必须要的 (1-9)。#ASCII数字或加/减符号是允许的,但不是必须要的。H十六进制数据字符是必须要的,A-F、a-f、0-9。h十六进制数据字符是允许的,但不是必须要的。B二进制数据字符是必须要的,0-1。b二进制数据字符是允许的,但不是必须要的。>所有的字符字母都大写<所有的字符字母都小写!关闭大小写转换
| 使用 \ 去转义上述列出的字符。
例子
mywidget
::mywidget()
{
setWindowTitle(
"my widget test");
QVBoxLayout
*layout
=new QVBoxLayout(this);
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();
}
mywidget
::mywidget()
{
setWindowTitle(
"my widget test");
QVBoxLayout
*layout
=new QVBoxLayout(this);
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();
}
mywidget
::mywidget()
{
setWindowTitle(
"my widget test");
QVBoxLayout
*layout
=new QVBoxLayout(this);
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(double_validator);
QLineEdit
*pline_edit2
=new QLineEdit();
pline_edit2
->setInputMask(
"000.000.000.000;_");
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();
});
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)
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();
}
he QScrollArea class provides a scrolling view onto another widget. 可以滚动的区域
功能设置
函数描述
void ignment(Qt::Alignment)对齐方式void setWidget(QWidget *widget)addwidgetvoid setWidgetResizable(bool resizable)自动调整大小
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);
pscroll_area
->setAlignment(Qt
::AlignCenter);
pscroll_area
->setWidgetResizable(
true);
layout
->addWidget(pscroll_area);
this
->setFixedSize(
300,
300);
this
->show();
}
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现在的indexQWidget * currentWidget() const现在的widgetint 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) constQIcon itemIcon(int index) const返回iconQString itemText(int index) const返回textQString itemToolTip(int index) const返回提示void removeItem(int index)移除void setItemEnabled(int index, bool enabled)void setItemIcon(int index, const QIcon &icon)设置iconvoid setItemText(int index, const QString &text)设置textvoid 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>
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;
}
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::Unknown0Unknown reasonQSystemTrayIcon::Context1The context menu for the system tray entry was requestedQSystemTrayIcon::DoubleClick2The system tray entry was double clicked.QSystemTrayIcon::Trigger3The system tray entry was clicked
消息图标ValueDescription
QSystemTrayIcon::NoIcon0No icon is shown.QSystemTrayIcon::Information1An information icon is shown.QSystemTrayIcon::Warning2A standard warning icon is shown.QSystemTrayIcon::Critical3A critical warning icon is shown.
小例子
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);
psystray->setIcon(QIcon(
":/image/wz2.jpg"));
psystray->setToolTip(
"i`m systemtray ,don`t click me!");
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) constQDateTime addMSecs(qint64 msecs) constQDateTime addMonths(int nmonths) constQDateTime addSecs(qint64 s) constQDateTime addYears(int nyears) constvoid setDate(const QDate &date)void setTime(const QTime &time)void setTimeSpec(Qt::TimeSpec spec)区域时间void setTimeZone(const QTimeZone &toZone)时区
判断
函数描述
bool isDaylightTime() constbool isNull() constbool isValid() const
格式转化
函数描述
CFDateRef toCFDate() constQDateTime toLocalTime() constqint64 toMSecsSinceEpoch() constNSDate * toNSDate() constQDateTime toOffsetFromUtc(int offsetSeconds) constqint64 toSecsSinceEpoch() constQString toString(const QString &format) constQString toString(Qt::DateFormat format = Qt::TextDate) constQString toString(QStringView format) constQDateTime toTimeSpec(Qt::TimeSpec spec) constQDateTime toTimeZone(const QTimeZone &timeZone) constQDateTime toUTC() const
格式控制
字符表示
hthe hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)hhthe hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)Hthe hour without a leading zero (0 to 23, even with AM/PM display)HHthe hour with a leading zero (00 to 23, even with AM/PM display)mthe minute without a leading zero (0 to 59)mmthe minute with a leading zero (00 to 59)sthe whole second without a leading zero (0 to 59)ssthe whole second with a leading zero where applicable (00 to 59)zthe fractional part of the second, to go after a decimal point, without trailing zeroes (0 to 999). Thus “s.z” reports the seconds to fullzzzthe fractional part of the second, to millisecond precision, including trailing zeroes where applicable (000 to 999).AP or Ause AM/PM display. A/AP will be replaced by either “AM” or “PM”.ap or ause am/pm display. a/ap will be replaced by either “am” or “pm”.tthe timezone (for example “CEST”)
QDateTimeEdit
时间日期函数,可以设置显示格式,时间范围,调用日历
set
函数描述
oid setCalendarPopup(bool enable)弹出日历选择void setCalendarWidget(QCalendarWidget *calendarWidget)弹出的日历窗体void setCurrentSection(QDateTimeEdit::Section section)设置现在的sessionvoid 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)设置当前的seeionvoid 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)
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();
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抽象的操作布局ItemQSizePolicy描述水平和垂直大小调整的策略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)添加spaceitemvoid 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返回长度
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;");
}
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的addstretchvoid setSpacing(int spacing)间距void setVerticalSpacing(int spacing)垂直间距columnCount()获取列数rowCount()获取行数
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);
pLayout
->setRowMinimumHeight(
3,
10);
pLayout
->setHorizontalSpacing(
10);
pLayout
->setVerticalSpacing(
10);
pLayout
->addWidget(pImageLabel,
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();
}
一般不常用,需要是看文档
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)添加widgetint currentIndex() const返回位置QWidget * currentWidget() const返回位置int insertWidget(int index, QWidget *widget)插入wedgetvoid setStackingMode(QStackedLayout::StackingMode stackingMode)void setCurrentIndex(int index)到达想去的wibgetvoid setCurrentWidget(QWidget *widget)到达想去的位置
signal
void currentChanged(
int index)
void widgetRemoved(
int index)
/*
*
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() constQDir的绝对路径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(AllEntriesNoDotAndDotDot)) constbool isReadable() const可读bool isRelative() const相对位置bool isRoot() const根目录bool exists(const QString &name) constbool 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
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");
allFile("E:/newfile1");
rmAll("E:/newfile1");
}
QFileInfo
提供一系列文件信息,前缀,后缀,大小,创建时间…..相当于文件的属性,详细信息
函数描述
QDir absoluteDir() const绝对位置的DirQDir dir() const返回dirQString absoluteFilePath() const路径名QString path() const路径名QString absolutePath() constQString 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文件主的idQString 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文件的组的idbool 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)
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);
}
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::Ok0The text stream is operating normally.QTextStream::ReadPastEnd1The text stream has read past the end of the data in the underlying device.QTextStream::ReadCorruptData2The text stream has read corrupt data.QTextStream::WriteFailed3The text stream cannot write to the underlying device.
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)
cout<<
out.readAll()<<endl
cout<<
out.device()<<endl
cout<<bin<<
5023.5/
1024.0
file
.close()
}
qt_文件运用,调用桌面
QFileSystemWatcher
函数描述
bool addPath(const QString &path)添加一个pathQStringList 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)文件改变
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
{
if (
!newFile
.isEmpty())
{
cout
<< "New Files/Dirs added: " ;
foreach (QString file, newFile)
{
cout
<<file
<<endl;
}
}
if (
!deleteFile
.isEmpty())
{
cout
<< "Files/Dirs deleted: " ;
foreach(QString file, deleteFile)
{
cout
<<file
<<endl;
}
}
}
}
QDesktopServices
函数描述
bool openUrl(const QUrl &url)打开一个urlvoid setUrlHandler(const QString &scheme, QObject *receiver, const char *method)定制.但是不会…void unsetUrlHandler(const QString &scheme)
QFileIconProvider
enum QFileIconProvider::IconType
ConstantValue
QFileIconProvider::Computer0QFileIconProvider::Desktop1QFileIconProvider::Trashcan2QFileIconProvider::Network3QFileIconProvider::Drive4QFileIconProvider::Folder5QFileIconProvider::File6
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();