Qt学习笔记(QAction,QString格式化输出)

来源:互联网 发布:阿里云幕布拍照要求 编辑:程序博客网 时间:2024/05/05 23:19

在编写界面程序时经常会用到单选项或者复选项,界面按钮方式可以采用QCheckBox、QRadioButton配合QGroupBox实现。如果采用Qt设计师设计界面时,很容易达到这样的效果。而另一种情况是采用菜单项实现,而菜单栏实现单选或者多选一般采用QAction实现。

使用QAction实现单选的方法:将多个QAction添加到QActionGroup,并将QActionGroup设置为exclusive即可,及setExclusive(true);

示例(action已经在设计师界面上定义):

    /*动静态切分算法action的互斥选择设置*/
    QActionGroup* algrithmAction = new QActionGroup(this);
    algrithmAction->addAction(ui->frameDifAlgAction);
    algrithmAction->addAction(ui->multiThrhldFramedifAction);
    algrithmAction->addAction(ui->vibeAlgAction);
    algrithmAction->setExclusive(true);

QString是在编写Qt程序时经常用到的数据结构,同时我们经常需要将各种类型的数据转化成QString然后输出到界面上。这是实现QString的格式化(如printf)就很有必要。

1.QString 转换成其他格式

QString转string:使用QString::toStdString()即可实现。

QString转数字:使用QString::toInt()/toDouble()/toFloat()/等等

QString转字符串:这个需要稍微麻烦一些

Qstring  str;

char*  ch;

QByteArray ba = str.toLatin1();    

ch=ba.data();

注意:不可以str.toLatin1().data()这样一步完成,可能出错,在需要多个字符串转化时就会出错,如果整个程序只有一次这样的转化可以尝试,安全起见,分步完成。


2.arg的使用

QString::arg ( int a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const

该方法可以实现一定功能的格式化转换,具体实现如下:

     int i = 10;           // current file's number
     int total = 100;       // number of files to process
     QString fileName = "fileNameTest";    // current file's name

     QString status = QString("Processing file %1 of %2: %3") .arg(i).arg(total).arg(fileName);
该方法是通过占位符的思想实现的,通过arg的参数替换相应位置的变量


3.sprintf

  • QString & QString::sprintf ( const char * cformat, ... )

    这个函数和 C 中的也是差不多的用法,只不过它作为QString的一个成员函数,使用起来就相当方便了,如:

       1: #include <QtCore/QCoreApplication>
       2: #include <iostream>
       3: #include <stdio.h>
       4: using namespace std;
       5: int main()
       6: {
       7:     QString str2;
       8:     str2.sprintf("Ggicci is %d years old, and majors in %s.", 20, "Software Eng");
       9:     cout << str2.toStdString() << endl;
      10:     return 0;
      11: }

输入结果:

Ggicci is 20 years old, and majors in Software Eng.
Press <RETURN> to close this window...

参考文章:http://tmjfzy.blog.163.com/blog/static/6644702520126464353569/


0 0
原创粉丝点击