QT3学习笔记(控件的使用)
2010-02-08 21:02

所有代码都是在qt3.3.8+fedora8下运行的。

1. 控件位置的确定
控件的位置一般来说是相对其父的其左上角的坐标:
QWidget *w = new QWidget(this);
QPoint p = w->pos();
int x = p.x();
int y = p.y();
若要得到其针对全局界面的坐标值,则需要转换一下,用mapToGlobal():
QPoint p(0, 0);
int x = mapToGlobal(p).x();
int y = mapToGlobal(p).y();

2. QWidget
(1) 对widget的显示和隐藏
QWidget *w = new QWidget(this);
w->setHidden(true); //隐藏
w->setHidden(false); //显示
(2) 用QWidget实现弹出窗口的效果
QWidget *w = new QWidget("test", this, "mySplashScreen", WStyle_Customize | WStyle_Tool );//WStyle_Splash
w->setMinimumSize(100, 100);
w->show();
实际上,弹出窗口QDialog就是来源于QWidget,所以能用QLabel这样的类定义出窗口效果也就不奇怪了。
另外用WidgetFlags的不同搭配还可以实现其它效果,如:
WStyle_Customize | WType_Modal //模式对话框(WType_Modal= WStyle_Dialog | WShowModal)
WStyle_Customize | WStyle_StaysOnTop | WType_TopLevel //弹出在最上端
注:在QT4里貌似用w->setWindowModality(Qt::WindowModal);也能实现模式对话框,但没验证过。

3. QLabel
(1) 定义
QLabel* m_labelOrdered = new QLabel("0", this);
(2) 对文字的左右对齐设置
m_labelOrdered->setAlignment(Qt::AlignLeft);//左对齐
其它还有,横向对齐:
Qt::AlignAuto – 根据语言内容,大部分是左对齐。右对齐的有:阿拉伯语、希伯来(现代以色列)语
Qt::AlignLeft – 居左
Qt::AlignRight – 居右
Qt::AlignHCenter – 居中
Qt::AlignJustify – 两端对齐。并不是所有时候都有效,有时会被AlignAuto中断
竖向对齐: 
Qt::AlignTop – 居顶
Qt::AlignBottom – 居底
Qt::AlignVCenter – 居中
同时只可以使用一个横向或竖向对齐方式。但是还有一个同时设置横竖方向的标记:
Qt::AlignCenter – 横竖都居中

内容自动换行:

QLabel::WordBreak

但是,帮助手册上说:BreakAnywhere标记在QLabel是不支持的。

如果一定有这样的需求,可以考虑下面两个方法:

(1) 在setText()时,用HTML串赋值,里面加上换行符

(2) 使用QTextEdit代替。设置:read-only/frame trued off/its palette's window/background brush set to no-brush。用QTextEdit还有一个好处,就是可以对内容进行赋值粘贴。

 

4. QPixmap
(1) 定义和赋值
QPixmap pix;
pix.load("images/typebutton.PNG");
QPixmap pix("images/typebutton.PNG");
QPixmap pix = new QPixmap("images/typebutton.PNG");
(2) 如何实现QT背景图片拉伸
方法一
int w = 10;
int h = 20;
QPixmap pix("test.png");
QImage qimage = pix.convertToImage(); 
qimage = qimage.scale(w, h, QImage::ScaleFree); 
pix.convertFromImage(qimage, QPixmap::Auto);
方法二(貌似是4.0以上版本的,没验证过)
QWidget *widget = new QWidget();
widget->setAutoFillBackground(true); // 这句要加上, 否则可能显示不出背景图.
QPalette palette = widget->palette();
palette.setBrush(QPalette::Window,
QBrush(QPixmap("1.png").scaled( // 缩放背景图.
        widget->size(),
        Qt::IgnoreAspectRatio,
        Qt::SmoothTransformation))); //使用平滑的缩放方式
widget->setPalette(palette); // 至此, 已给widget加上了背景图.
(3) 对图片灰度的处理
QImage qimage = pix.convertToImage(); 
pix.convertFromImage(qimage, QPixmap::Mono);//黑白,而且颗粒感很强,不太好看
(4) 背景图片按实际大小比例显示
首先,覆盖控件的paintEvent事件
然后,在事件处理时获得控件的实际大小
最后,按照上面的方法一拉伸背景图片,再覆盖原背景图片
代码如下:
//m_pmBackGroundPixmap是要显示的背景图片(QPixmap)
//m_lbPixLabel是自定义label控件(QLabel)
//getStretchPixmap(int w, int h, QPixmap pix)是按照6方法写的公共函数
void BPixmapButtonBase::paintEvent( QPaintEvent *e)
{
    QRect rect = e->rect();
    m_pmBackGroundPixmap = getStretchPixmap(rect.width(), rect.height(), m_pmBackGroundPixmap);//
    m_lbPixLabel->setBackgroundPixmap(m_pmBackGroundPixmap);
}
(5) qt中显示gif、png、jpg和jpeg图片
转自:http://hi.baidu.com/ys_shuoshu/blog/item/d53cbfbd20a9710619d81fff.html
qt中显示gif和png图片的方法比较简单,在编译libqte-mt.so文件时分别添加参数-qt-gif和-qt-libpng就可以了。
显示jpg和jpeg图片就稍微复杂一点,首先编译libqte-mt.so文件时要添加参数-qt-libjpeg和-qt-imgfmt-jpeg,然后拷贝plugins下的imageformats目录到文件系统目录下,我放在了/qte/plugins下,最后在main函数中添加QApplication::addLibraryPath("/qte/plugins");这样显示jpg和jpeg图片的环境就准备好了。
显示图片的使用setPixmap(<路径>);方法
补充:这里使用的qt版本为3.3.8
(6) 用QImage实现图片压缩(改变尺寸大小)
通过缩小图片的尺寸来实现图片的压缩,实际上就是上面图片拉伸的另一种应用。
首先,将原始文件读到QImage对象里;再用scale()函数设置目标尺寸;再用save()函数保存到本地。
bool QImage::save(const QString &fileName, const char* format, int quality=-1) const
fileName:可以是相对路径,也可以是绝对路径
format:想保存的图片格式。常用的有:JPEG、PNG、BMP
要想知道一个图片的格式是什么,可以用函数:
const char* QImage::imageFormat(const QString &fileName) [static];
例子:
QImage im("images/testimage.jpg"); //大小为 73.3KB
im = im.scale(50, 50, QImage::ScaleFree);
if(im.save("images/small_testimage.jpg", "JPEG")) //大小为 1.8KB
    qDebug("ButtonGroupForm::testImage save success!");
else
    qDebug("ButtonGroupForm::testImage save fail!");

5. QString
(1) 给QString赋值
QString s = “sss”;
也可以:
s.sprintf(“sss %d”, 2);
(2) int怎么转换成QString
int i=0;
//静态函数的方法
QString s = QString::number(i, 10);//10表示10进制,也可以不写,默认就是10进制
//非静态函数的方法
QString::setNum ( ulong n, int base = 10 ) 
这两个函数同样使用于其他数字类型,如:uint, long, float, bouble等
(3) float、double转换成QString
同上面的函数相同,若想规定输出格式,则可通过参数设定。
QString QString::number ( double n, char f = 'g', int prec = 6 ) [static]
setNum()也一样。f是表示输出的格式,prec是保留的小数位数,被截取的部分四舍五入。
Format Meaning
e format as [-]9.9e[+|-]999
E format as [-]9.9E[+|-]999
f format as [-]9.9
g use e or f format, whichever is the most concise
G use E or f format, whichever is the most concise
例1:
double d = 12.34;
QString ds = QString( "'E' format, precision 3, gives %1" ).arg( d, 0, 'E', 3 );
// ds == "1.234E+001"
例2 保留两位小数:
float f = 1.2;
float f2 = 1.567;
qDebug("inputForm::init : s=" + QString::number(f, 'f', 2)); //s=1.20
qDebug("inputForm::init : s2=" + QString::number(f2, 'f', 2));//s2=1.57
(4) QString怎么转换成其它类型
若是int、float等数字型,有直接的对应转换函数。如:toInt(bool *ok=0, int base=10)等
QString s = "10";
int i = s.toInt();
若是char*型,则有:ascii()。如:
char *c = s.ascii();
(5) 怎么比较两个QString的内容
直接使用==,>=, <=,<,>,!=等。
(6) 取子串
QString支持取左、取右、取中间,如下:
QString s(“Five pineapples”);
QString l = s.left(4); //l = “Five”
QString r = s.right(6); //r = “apples”
QString m = s.mid( 5, 4 ); // t = “pine”

6. QLineEdit
(1)密码框的实现
QLineEdit,将echoMode属性设置成:Password
这样,输入的字符都是圆点显示

7. QDialog
(1)动态定义、弹出对话框
qt对话框类是QDialog ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 ) 
modal:指是否模式对话框,也可以用setModal(bool)改变设置;
f:指窗口的样式。
如:
DDishDetailForm *dishDetailForm = new DDishDetailForm( this->parentWidget(), "dishdetailform", TRUE, WStyle_Customize | WStyle_NoBorder);
定义了一个DDishDetailForm的弹出窗口,模式对话框,无边框。
弹出对话框,可以用:
dishDetailForm->show();//显示的模式按照对应的为准
也可以用:
dishDetailForm->exec();//则无论定义的modal设置的是什么,都按照模式对话框显示

(2) 使用QTDesigner导航生成的Form
虽然导航生成的Form也是继承自QDialog,但是它封装了构造函数和析构函数。但是它分别在两个函数里默认调用了init()和destroy()两个函数。
所以要想做什么初始化的操作就定义一个init()函数,写在里面。
要想在析构函数里做什么就定义一个destroy()函数,写在里面。

8. QComboBox
(1)属性设置
设置下拉的高度,高度是可见的item行数:
comboBox->setSizeLimit(5); //5行
如果不想使用滚动条,而是固定高度,横向扩展显示,则做下面设置即可:
m_comboBox->listBox()->setColumnMode(QListBox::Variable);//默认即是
m_comboBox->listBox()->setVariableWidth(true); //使下拉列表的宽度可变
m_comboBox->listBox()->setRowMode(QListBox::FitToHeight); //行数和下拉的高度一致(不出现滚动条)
chartTypeTextLabel->setBuddy( chartTypeComboBox );

9. QTable
详见《QTable使用详解.doc》

10. QDate、 QTime and QDateTime
QT提供了三个日期时间方面的类:QDate、QTime、QDateTime。使用方法都差不多,也非常方便。三个类都包含在头文件<qdatetime.h>中。
(1) 以QDateTime为例,说明获取当前时间的使用方法。
方法:currentDataTime()
因为是静态函数,所以不需要定义对象。返回的是QDateTime对象,若想转换成格式字符串,使用toString()函数即可。例子如下:
QString ss = (QDateTime::currentDateTime()).toString("yyyy-MM-dd hh:mm:ss");// 2010-02-20 15:55:51
(2) 用QTime计算运行时间
方法:int elapsed() const
用这个函数可以很方便的测试出一段代码运行所需要的时间,而不需自己手动计算。
QTime t;
//开始第一次计算
t.start();
//…要运行的代码段…
qDebug( "Time elapsed: %d ms", t.elapsed() );
//开始第二次计算
t.restart();
//…要运行的代码段…
qDebug( "Time elapsed: %d ms", t.elapsed() );

11. QProgressDialog
我们处理耗费时间的操作时经常会用到滚动条。直接上代码:
#include <qapplication.h>
int NumRows = 10;
QProgressDialog progress(tr("Saving file..."), tr("Cancel"), NumRows);
progress.setModal(true);
for (int row = 0; row < NumRows; ++row) {
    progress.setProgress(row);
    qApp->processEvents();
    if (progress.wasCanceled()) {
        //dosomething
        return;
    }
}
说明:
NumRows,进度条的总步数,QProgressDialog会根据这个数自动算出每一步走多少长度。
QApplication::processEvents()用来处理任何repaint事件(如,接受用户点击Cancel按钮)(但是好像不写这句也可以)。
我们不调用show()函数,是因为QProgressDialog自己已经做了。如果这个过程变得极短,则dialog根本不会被显示。

posted on 2012-06-24 11:51  kangwang1988  阅读(4915)  评论(0编辑  收藏  举报