7.2 QT常用图形组件
字符串类QString
一、操作字符串
1、QString 提供了一个二元的“+”操作符组合两个字符串,并提供一个“+=”操作符将一个字符串追加到另一个字符串的末尾。
eg1:
QString str1 = "welcome ";
str1 = str1+ "to you! ";//str1 = welcome to you!
QString str2="hello, ";
str2 += "world!";//str2 = "hello,world!";
2、QString::append()函数具有和+=操作符一样的功能,实现在一个在一个字符串的末尾追加另一个字符串。
eg:
QString str1 = "welcome ";
QString str2 = "to";
str1.append(str2);//str1 = "welcome to";
str1.append("you!");//str1 = "welcome to you!";
3、组合字符串的另一个函数是QString::sprintf(),此函数支持的格式定义符和C++库中的函数srintf()定义的一样。
eg:
QString str;
str.sprintf("%s","welcome");//str="welcome"
str.sprintf("%s %s","welcome ","to you!");//str="welcome to you!"
4、QT还提供了另一种方便的字符串组合方式,使用QString::arg()函数,此函数的重载可以处理很多的数据类型。
eg:
QString str;
str=QString("%1 was born in %2").arg("crmn").arg(1990); //str = "crmn was born in 1990"
二、查询字符串数据
查询字符串数据有很多方式,具体如下:
1、函数startWith()判断一个字符串是否是以某个字符串开头。
eg:
QString str = "welcome to you!";
str.startWith("welcome",Qt::CaseSensitive);//返回true;
str.startWIth("you",Qt::CaseSensitive); //返回false;
2、类似于startWith(),endWith()函数判断一个字符串是否是以某个字符串结尾。
3、函数QString::contains()判断一个指定的字符串是否出现过。
eg:
QString str = "welcome to you!";
str.contains("welcome",Qt::CaseSensitive); //返回true
三、字符串的转换
1、QString::toInt()函数讲将字符串转换为整数类型,类似的函数还有toDouble()、toFloat()、toLong()、toLongLong()等。
eg:
QString str = "125";
bool ok;
int hex = str.toInt(&ok, 16); //ok = true,hex = 293
int dec = str.toInt(&ok, 10); //ok = true,dec = 125
2、Number转换成QString
static QString number(int, int base=10);
static QString number(uint, int base=10);
static QString number(long, int base=10);
static QString number(ulong, int base=10);
static QString number(double, char f = 'g',int prec = 6);
QT基本图形组件
eg:QLabel/标签 QPushButton/按钮 QLineEdit/行编辑 QRadioButton/单选框 QCheckBox/复选框 QComboBox/组合框
















1 void MainWindow::on_btnCompute_clicked()
2 {
3 int num1 = ui->txtNum1->text().toInt();
4 int num2 = ui->txtNum2->text().toInt();
5 double numResult;
6 if(ui->radAdd->isChecked())
7 numResult = num1 + num2;
8 else if(ui->radSub->isChecked())
9 numResult = num1 - num2;
10 else if(ui->radMul->isChecked())
11 numResult = num1 * num2;
12 else if(ui->radDiv->isChecked())
13 {
14 if(num2 != 0)
15 numResult = (double)num1/num2;
16 }
17 ui->lblResult->setText(QString::number(numResult));
18 }
浙公网安备 33010602011771号