qrect的使用 qt_[Qt]常用实用Qt小模块(经典)

本文介绍了Qt编程中的实用模块,包括正则表达式验证、QObject的connect方法、QLineEdit的使用、信号与槽的定义及发射、窗口大小调整、QList的管理、Qt迭代器操作、QTableWidget应用、窗口属性设置、QSettings的使用、事件处理、窗口与子部件管理、信号槽机制、各种对话框的使用等,深入浅出地展示了Qt开发中的常见功能和技巧。

0:website

1:QRegExp 正则表达式

QRegExp regExp("[a-zA-Z][1-9][0-9]{0,2}");

xxx->setValidator(new QRegExpValidator(regExp,this));

lineEdit->setValidator(new QRegExpValidator(regExp,this));

2:QObject::connect()

connect(objectA,SIGNAL(methodA()),objectB,SLOT(methodB()));

//methodA()的输入参数可以比methodB()的参数多

3:QLineEdit 行文字输入widget

lineEdit->hasAcceptableInput(); //返回true or false

lineEdit->setText("please input text");

button->setEnabled(true); //set true or false

4:信号函数的定义和发射

class A {

Q_OBJECT

signals:

void funs(type A,type B); //定义信号函数

};

type a;type b;

emit funs(a,b);

//发射上面定义的信号函数 ,当然需要使用QObjetc::connect()这个函数 把这个信号函数与真实的slot函数绑定起来,slot函数才是真正干活的函数

5:Qt中可以动态调整窗口大小的Widget有哪些

QTabWidget

QListWidget 和 QStackedWidget 配合使用

QTreeWidget 和 QStackedWidget 配合使用

6:对一个继承QDialog的类,能动态改变窗口大小的方法如下:

//隐藏必要的子Widget

xx->hide();

yy->hide();

//下面这个方法非常关键,会根据xx,yy子widget是否显示,动态调整窗口的大小

layout()->setSizeConstraint(QLayout::SetFixedSize);

7:创建一个Qt风格的子类

class MyClass: pulbic QObject

{

public:

MyClass(const string& text,QObject *parent=0);

};

MyClass::MyClass(const string& text,QObject *parent): QObject(parent)

{

//构造函数的定义

}

8:QList的使用例子

QList list;

list<

foreach(QString a,list)

qDebug()<

#相当好用的QList

QList list;

list << "first";

list.append( "second" );

list.prepend( "third" );

list.insert( 1, "fourth" );

list.insert( 4, "fifth" );

9:Qt迭代器的用法

QList list;

list << 23 << 27 << 52 << 52;

QListIterator javaIter( list );

while( javaIter.hasNext() )

qDebug() << javaIter.next();

QList::const_iterator stlIter;

for( stlIter = list.begin(); stlIter != list.end(); ++stlIter )

qDebug() << (*stlIter);

10:使用迭代器修改list的元素

QList list;

list << 27 << 33 << 61 << 62;

QMutableListIterator javaIter( list );

while( javaIter.hasNext() )

{

int value = javaIter.next() + 1;

javaIter.setValue( value );

qDebug() << value;

}

QList::Iterator stlIter;

for( stlIter = list.begin(); stlIter != list.end(); ++stlIter )

{

(*stlIter) = (*stlIter)*2;

qDebug() << (*stlIter);

}

11:所有widget的分类

button:

QPushButton

QToolButton

QRadioButton

box:

QCheckBox

QGroupBox

QToolBox

QSpinBox

QDoubleSpinBox

QComboBox

edit:

QLineEdit

QTextEdit

QDateEdit

QTimeEdit

QDateTimeEdit

widget:

QTabWidget

view:

QListView

QTreeView

QTableView

dialog:

QInputDialog

QProgressDialog

QColorDialog

QFontDialog

QPageSetupDialog

QFileDialog

QPrintDialog

others:

QFrame QLabel QLCDNumber QProgressBar

QTextBrowser QSlider QDial

QMessageBox QErrorMessage

12:在主窗口程序中打开新的dialog对话框的方式

#1 阻塞式:(主窗口的内容是无法访问的)

QDialog dialog;

Ui_Dialog a;

a.setupUi(&dialog);

if(dialog.exec()) // 当点下ok button时会返回accept=true,当点下cancel时会返回reject=0

{

}

#2 非阻塞式:(访问子dialog的同时,也能访问父窗口)

findDialog=new FindDialog(this);

connect() //把finddialog的信息 传递给接受信息,处理信息的槽函数

findDialog->show();

findDialog->raise();

findDialog->activateWindow();

13:关于QTableWidget的使用

QTableWidget * spreadsheet=new QTableWidget(this);

setCentralWidget(spreadsheet);//这个方法是QMainWindow的方法

#得到当前鼠标focus的单元格的行坐标和列坐标

spreadSheet->currentRow()

spreadSheet->currentColumn()

#得到当前单元格的内容

//如果当前单元格内没有内容,if内容为NULL

if(spreadSheet->currentItem())

{

cout<currentItem()->text()<

}

#鼠标focus的单元格位置发生变化时,触发如下信号函数

currentCellChanged(int,int ,int,int)

14:主窗口widget常用的方法

setWindowTitle();

setWindowIcon(QIcon("xx.png"));

#在QMainWindow中如何添加菜单栏和工具栏

#创建需要 action

newAction=new QAction("&new",this);

newAction.setIcon(QIcon("xx.png"));

connect(newAction,SIGNAL(),object,SLOT()); //让action干相应的活

#添加一个菜单栏

QMenu *fileMenu=menuBar()->addMenu("&File");

fileMenu->addAction(neAction);

fileMenu->addSeparator();

#添加一个QToolBar

QToolBar * fileToolBar= addToolBar("&file");

fileToolBar->addAction(newAction);

fileToolBar->addSeparator();

//menufile->addSeparator()这个函数也是返回一个QAction *类型的数据

#在statusBar()中添加widget

statusBar()->addWidget(label);

statusBar()->addWidget(label,1); //从左开始放label,1表示用空白扩展剩下的右边空间

statusBar()->showMessage(const QString & str);

15:QLabel的所有设置

QLabel * label=new QLabel("w999");

label->setAlignment(Qt::AlignHCenter);//文字对齐方式

label->setMinimumSize(label-sizeHint());//文字宽度最少4个字符,当QLabel中没有字符时,也会保证最少有4个字符的空白位置显示

16:QSettings的用法

#创建settings对象

QSettings settings("Yzs_think", "Application");

公司或组织名称:Yzs_think, 程序名称:Application

#从settings中读出数据,设置应用程序的相关参数,可以设置默认值

QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();

QSize size = settings.value("size", QSize(400, 400)).toSize();

resize(size);

move(pos);

#程序退出前,把需要保存的参数保存到settings中,书上说是保存到注册表中去了,还没有实践过

QSettings settings("Yzs_think", "Application");

settings.setValue("pos", pos());

settings.setValue("size", size());

17:窗口重要属性设置

#保证容器一直在top layer(就是常用的fix 窗口在顶层)

w.setWindowFlags(Qt::WindowStaysOnTopHint);

18:各类event函数调用的条件

//event函数被调用,分为下面几种情况:

1:用户对mouse and keyboard的操作

2:定时器时间到了

3:网络超时

4:窗口管理器

1:上面是4类称为event sources,事件产生的源头

2:event object:这个就是包含事件源有何种改变的事件对象( 如QPressedEvent *e)

3:event target,这处就是事件会通知给谁(一般就是事件处理函数)

一句话说:event sources发生的事件变化,包装到event object中,传递给event target

//窗口大小发生变化时,或是鼠标从一个widget到另一个widget时移动时, 程序启动时会在构造函数调用调用之后,调用 paintEvent函数(参数类型不能写错)

void paintEvent(QPaintEvent *)

//点了右上角的x时,会调用该方法

void closeEvent(QCloseEvent *)

19:关于Qt中的主窗口

qt中的主窗口是是没有父窗口的

有父窗口的widget,称为子部件

Qt::WindowFlags作为父窗口的第二个参数,可以定义父窗口很多重要属性:如下

Qt::Widget

Qt::Dialog

Qt::SplashScreen

#保证容器一直在top layer(就是常用的fix 窗口在顶层)

w.setWindowFlags(Qt::WindowStaysOnTopHint);

#函数对窗口进行最大,最小化,全屏操作

setWindowState()

#对于主窗口,我们非常关心窗口的大小和出现的位置,下面的函数是getter,

主窗口包含两部分:

1:框架部分(如title and border):使用x(),y(),pos(),move(),frameGeometry()函数访问

2:内容部分,称为无框架的窗口:使用width(),height(),geometry(),setGeometry(),Rect(),Size()函数访问 ,resize()函数是调整内容部分的大小。

综上:使用move(),setGeometry()两个函数设置窗口出现在桌面的位置和窗口的长宽。

w.setGeometry(QRect(0,0,400,400));//这里的0,0,是.geometry().x() .y()的值设置为0

w.move(0,0);//这里的0,0是pos().x() .y()的值设置为0

#setFixedSize(size.Hint())//固定主窗口的大小为不可改变

通常如下,设置父窗口的大小位置

w.setGeometry(QRect(0,0,400,400));

w.move(0,0);

#w.frameGeometry() 这个是外边框的信息 .x() .y() .width() .height()

#w.geometry() 是内部内容部分的信息 .x() .y() .width() .height()

.resize(w,h)函数 调整大小,是内容部分的宽高

This property holds the size of the widget excluding any window frame.

19:Qt creator中,断点调试方法

在程序代码行号前单击,确定断点,再点击,取消断点

按F5,程序进入断点调试过程,比较慢,不是大的问题,不需要用这样的方法调试,太耗费资源时间了

断点的好处就是方便的观察变量的值

20:从下面的图可以看到frameGeometry是外边框,geometry是内容窗口(内容窗口包含在外加框里面,所以尺寸更小)

geometry : QRect

This property holds the geometry of the widget relative to its parent and excluding the window frame.

frameGeometry : const QRect

This property holds geometry of the widget relative to its parent including any window frame.

21:父窗口与子widget

指明了父窗口的子widget,可以不用显式的delete掉,父窗口会处理好后面的垃圾回收工作

模态窗口与模态窗口(根据需要进行选择show() or exec())

另一种实现modal态的方法:(阻塞态)

(这种方法可以使窗口为阻塞态的同时,程序还可以处理其它的事情,因为调用 了show()之后,控制权就给调用者了)

QDialog *d=new QDialog(this);

d->setModal(true);

d->show();

setWindowModality(xx)://xx可取下三值 :

Qt::NonModal :不阻塞

Qt::WindowModal :阻塞父,祖窗口,和他们的子窗口

Qt::ApplicationModal :阻塞所有窗口,setModal(true)就是达到这一效果

22:信号和槽

signal and slot的作用是完成对象之间协同工作,如信息的传递,事件的响应

close() 槽一般是隐藏窗口,只有当 当前widget是最后一个窗口时,才会delete掉

Closes this widget. Returns true if the widget was closed; otherwise returns false.

First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. If it ignores the event, nothing happens. The default implementation of QWidget::closeEvent() accepts the close event.

If the widget has the Qt::WA_DeleteOnClose flag, the widget is also deleted. A close events is delivered to the widget no matter if the widget is visible or not.

The QApplication::lastWindowClosed() signal is emitted when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus.

23:Qt自带的不同dialog的使用

#1: 颜色对话框

QColor color=QColorDialog::getColor(Qt::red,this,tr("颜色对话框"));

QColor color=QColorDialog::getColor(Qt::red,this,tr("颜色对话框"),QColorDialog::ShowAlphaChannel);//可以设置颜色的alpha值

#2: 颜色对话框

QColorDialog dialog(Qt::red,this);

dialog.setOption(QColorDialog::ShowAlphaChannel);

dialog.exec();

QCoolor color=dialog.currentColor();

#3: 文件对话框 返回的是包含绝对路径的文件名

QString fileName=QFileDialog::getOpenFileName(this,tr("文件对话框"),"D:",tr("图片文件(*.png *.jpg)"));

#4:文件对话框 返回多个文件名

QStringList fileNames=QFileDialog::getOpenFileNames(this,tr("文件对话框"),"D:",tr("图片文件(*.png *.jpg)"));

#5: 文件对话框(保存文件,另存)

QFileDialog::getSaveFileName();

#6: 得到已存在文件夹的路径

QFileDialog::getExistingDirectory();

#7:得到字体对话框(设置对象字体时需要)

bool ok;

QFont font=QFontDialog::getFont(&ok,this)

if(ok)

{ //yes u select a font

xx->setFont(font);![图片描述][1]

}

else

{

}

#8:得到用户输入对话框:QInputDialog

QInputDialog::getText(xx);

QInputDialog::getInt(xx);

QInputDialog::getDouble(xx);

QInputDialog::getItem(xx);

#9信息对话框 :QMessageBox

QMessageBox::information();

QMessageBox::quesiton();

QMessageBox::warning();

QMessageBox::critical();

QMessageBox::about();

24:QProgressBar(经常需要用到的)

25:QWizard 用来实现软件的使用介绍指南是非常不错的(引导用户学习软件的使用方法)

QWizardPage * createPage()

{

QWizardPage * page=new QWizardPage;

page.setTitle("开始学习");

return page;

}

QWizard *wizard=new QWizard(this);

wizard->setWindowTitle("软件使用指南");

wizard->addPage(createPage());

wizard->exec();

delete wizard;

26 与打印有关的几个对话框

QPageSetupDialog --- QPrintDialog --- QPrintPreviewDialog

27 QMainWindow

28 Qt实用小功能

#QString

QString a="hello";

QString b="world";

QString c=a+" "+b;

c.append(" ok");

c.prepend("head ");

QString::number(string.size());

string.toUpper();

string.toLower();

#目前使用Qt的版本

qVersion();//return char *

#Qt的标准输出流

QTextStream out(stdout);

out << "console application\n";

#Qt文件的写入

QFile data("filename");

if (data.open(QFile::WriteOnly)) {

QTextStream out(&data);

out << "You make me want to be a better man." << endl;

}

#Qt文件的读出

QFile data("filename");

QString line;

if (data.open(QFile::ReadOnly)) {

QTextStream in(&data);

in.setCodec("UTF-8"); //设置utf文件编码

do {

line=in.readLine();

}while(!line.isEmpty());

}

#QList

QTextStream out(stdout);

QList list;

list << "Balzac" << "Tolstoy" << "Guldbrassen"

<< "London" << "Galsworthy" << "Sienkiewicz";

qSort(list);

for (int i = 0; i < list.size(); ++i) {

out << list.at(i) << endl;

}

#QDir

QTextStream out(stdout);

QString home = QDir::homePath();

out << home << endl;

#得到某一目录下的特定类型文件名

QTextStream out(stdout);

QDir dir;

QStringList filters;

filters << "*.c" << "*.c~"; //对不需要的文件进行过虑

dir.setNameFilters(filters);

QFileInfoList list = dir.entryInfoList();

for (int i=0; i

QFileInfo fileInfo = list.at(i);

out << QString("%1").arg(fileInfo.fileName()); /文件名在这里

out << endl;

}

#QTime

QTime qtime = QTime::currentTime();

QString stime = qtime.toString(Qt::LocalDate);

29:Qt的QBoxLayout and QGridLayout

QHBoxLayout * hlayout =new QHBoxLayout();

hlayout->addWidget(QWidget *, int stretch=0,Qt::Alignment alignment=0);

QGridLayout * glayout =new QGridLayout();

glayout->addWidget(QWidget *,int row, int col,int rowspan=1,int colspan=1,Qt::Alignment alignment=0);

QFormLayout

QStackedLayout

30:关于QWidget的sizeHint

sizeHint();

minimumSizeHint();

对于每个widget,都有这两个函数,用来保存部件的建议大小尺寸和最小大小尺寸

当我们使用了下面的函数,设置了最小大小后,就不会用minimumSizeHint的大小了

pushButton->setMinimumSize();

setSizePoliy()这个函数对于设置widget的尺寸大小非常重要

下面的函数用来 读取 和 设置 widget的sizePolicy属性

pushButton->sizePolicy();

pushButton->setSizePolicy(QSizePolicy::Policy horizontal QSizePolicy::Poliyc vertical );

QSizePolicy的取值有:

QSizePolicy::Minimum :sizeHint提供的值是最小的尺寸

QSizePolicy::Maximum :sizeHint提供的值是最大的尺寸

QSizePolicy::Fixed :只能使用sizeHint的值,也可使用setFixedSize函数定死widget的大小

QSizePolicy::Expanding :最合适的大小为sizeHint,但是可压缩,不过倾向于expanding

QSizePolicy::Preferred :最合适的大小为sizeHint,可升可缩

QSizePolicy::MinimumExpanding :sizeHint提供的值是最小的尺寸,倾向于expanding

QSizePolicy::Ignored ;不考虑sizeHint的值,有多大变多大

#使用例子

QSizePolicy policy ;

policy.setHorizontalStretch(1);

policy.setVerticalStretch(1);

policy.setHorizontalPolicy(QSizePolicy::Minimum);

button->setSizePolicy(policy);

pushButton3->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);

31:Qt中文件名的解析例子

QString filename="/abc/9.jpg";

QFileInfo qfile(filename);

qcout<

qcout<

qcout<

qcout<

qcout<

#实用小例子:

QString filename="/root/abc/10.jpg";

QFileInfo qfile(filename);

QString extension=qfile.completeSuffix(); //得到后缀jpg

QString absoluteFnNoExtension=QString(filename).remove("."+extension);// 去除后缀 /root/abc/10

QString alphaname=absoluteFnNoExtension+"_alpha."+extension; //产生其它需要的文件名

32:Qt中QString 到char *pt的转化

QString one="11.jpg";

QString two="22.jpg";

QString three="33.ddd";

//这一步是必需要的,没有这个中间过程会产生问题

string cone=one.toStdString();

string ctwo=two.toStdString();

string cthree=three.toStdString();

const char *pone=cone.c_str();

const char *ptwo=ctwo.c_str();

const char *pthree=cthree.c_str();

33:Qt中得到格式化后人DateTime

##日期时间格式化字符串,也是比较容易的(要懂英语哦)

###以显示年为例,通常我们的年份都是4个数字,year是年的单词

###那么用yyyy就表示年的占位符

###有个问题:月month的占位符和分钟minute的占位符都是mm??怎么办

###解决办法是月的占位符用M,分钟的占位符用mm

###理解了上面的原则后,就不需要死记硬背了哦

QDateTime nowDateTime=QDateTime::currentDateTime();

//QString nowDateTimeStr=nowDateTime.toString("yyyy-M-dd hh:mm:ss");

QString nowDateTimeStr=nowDateTime.toString("yyyy/M/dd hh:mm:ss");

ui->dateTimeLabel->setText(nowDateTimeStr);

33:QSignalMapper的使用方法

QSignalMapper * mapper=new QSignalMapper(this);

mapper->setMapping(button0,"0");

mapper->setMapping(button1,"1");

...

connect(button0,SIGNAL(clicked()),mapper,SLOT(map()));

connect(button1,SIGNAL(clicked()),mapper,SLOT(map()));

connect(mapper,SIGNAL(mapped(QString)),this,SLOT(buttonClicked(QString)));

#工作方法:

#当button0发生clicked()信号后,会调用map()槽

#map()曹函数会根据setMapping里面设置的QString,发送一个mapped(QString)信号

#然后这样就会调用 buttonClicked(QString)这个槽函数,根据QString的数据,

#就可以知道用户点击了哪个按键!

#当有很多button,并且希望在一个槽函数中,处理所有clicked事件时,可以使用

#QSignlaMapper实现

34:Qt中不需要原生的最大最小化框架,设置主窗口背景的颜色和透明程度方法(高级)

#Qt中经常需要隐藏原生的最大最大小化按钮,然后定制自己的最大,最小化方式,下面是常用的方法

#在构造函数中使用如下函数

setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //无原生框架,最前端显示

setAttribute(Qt::WA_TranslucentBackground, true); //如果需要主窗口背景透明,调用这个函数

#如果需要设置主窗口的背景颜色和透明的程度,可以在paintEvent函数中调用如下函数 :

QPainter painter(this);

painter.fillRect(this->rect(), QColor(255, 255, 255, 0)); //前三个数值为颜色,最后一个值为alpha通道,即是透明程度(0全为背景全透明,即看到不背景)

#注意,看调用 setAttribute(Qt::WA_TranslucentBackground, true);函数后,背景默认是全透明的!

34:设置主窗口或QFrame的边框为圆角的方法(可能有更简单的方法)

#paintEvent事件处理函数中,使用如下方式实现

QBitmap bmp(ui->frame->size());

bmp.fill();

QPainter p(&bmp);

p.setBrush(Qt::black);

p.setRenderHint(QPainter::Antialiasing); //抗锯齿

p.drawRoundedRect(bmp.rect(), 5, 5); //四个角都是圆弧

//只要上边角圆弧

int arcR = 5; //弧度

QRect rect = this->rect();

// QPainterPath path;

// //逆时针

// path.moveTo(arcR, 0);

// path.arcTo(0, 0, arcR * 2, arcR * 2, 90.0f, 90.0f);

// path.lineTo(0, rect.height());

// path.lineTo(rect.width(), rect.height());

// path.lineTo(rect.width(), arcR);

// path.arcTo(rect.width() - arcR * 2, 0, arcR * 2, arcR * 2, 0.0f, 90.0f);

// path.lineTo(arcR, 0);

// p.drawPath(path);

// p.fillPath(path, QBrush(Qt::Red)); //arm和windows平台没有这行代码将显示一个透明的空空的框

ui->frame->setMask(bmp);

35:使用QSS管理全局样式的方法

#对于一个不大的项目,一到两个人维护时,把所有Widgets的样式放到一个qss文件中,是理想的选择

#设置方法如果,在Qt designer中preview样式后(alt+shift+R)后,就可以把样式复制qss文件中了

QApplication a(argc, argv);

setStyle(":/style/qss.qss");

#补一个实用的qss,button默认的边框和白色背景不显示的方法,

ui->closeButton->setStyleSheet("border-style:hidden;");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值