一、把字符串转换成整形
demo1:
QString str = "FF";
bool ok;
int hex = str.toInt(&ok, 16); // hex == 255, ok == true
int dec = str.toInt(&ok, 10); // dec == 0, ok == false
demo2:
bool ok;
QString line = "123";
int line1 = line.toInt(&ok); //把字符串“123”转换成整形的123
二、把整形转换成字符串
demo1:
long a = 63;
QString s = QString::number(a, 16); // s == "3f"
QString t = QString::number(a, 16).toUpper(); // t == "3F"
demo2:
int line4 = 123;
QString line4_4;
line4_4 = QString::number(line4); //把整形的123转换成字符串的"123"
三、获取输入对象中的字符串
QString line2 = ui->line1->text();
//line1为输入对象,把line1中的字符串保存在line2中
四、设置输入对象中的字符串
ui->line4->setText("hello");
//输入框中显示"hello"
使用例子:根据输入的运算符号进行两个数的加减乘除运算,让后点击一下按钮自动进行运算。
头文件:mainwindow.h
1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include <QMainWindow> 5 6 namespace Ui { 7 class MainWindow; 8 } 9 10 class MainWindow : public QMainWindow 11 { 12 Q_OBJECT 13 14 public: 15 explicit MainWindow(QWidget *parent = 0); 16 ~MainWindow(); 17 18 private slots: 19 void on_jieguo_clicked(); //槽函数,不懂的话可以看看我这篇的QT中槽的使用 20 21 private: 22 Ui::MainWindow *ui; 23 }; 24 25 #endif // MAINWINDOW_H
源文件:mainwindow.cpp
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 #include <QDebug> 4 #include <crtdefs.h> 5 #include <limits.h> 6 #include <stdlib.h> 7 #include <stdio.h> 8 9 MainWindow::MainWindow(QWidget *parent) : 10 QMainWindow(parent), 11 ui(new Ui::MainWindow) 12 { 13 ui->setupUi(this); 14 //建立槽连接 15 connect(ui->jieguo,SIGNAL(clicked(bool)),this,SLOT(MainWindow::on_jieguo_clicked())); 16 } 17 18 MainWindow::~MainWindow() 19 { 20 delete ui; 21 } 22 23 void MainWindow::on_jieguo_clicked() 24 { 25 QString line1 = ui->line1->text();//读出输入到line1中的字符串 26 QString line2 = ui->line2->text(); 27 QString line3 = ui->line3->text(); 28 QString line5; 29 30 bool ok; 31 int line4_4 = 0; 32 int line1_1; 33 int line3_3; 34 line1_1 = line1.toInt(&ok); //把字符转换成整形 35 line3_3 = line3.toInt(&ok); 36 if(!ok) 37 { 38 return; 39 } 40 else if(line2 == "+") 41 { 42 line4_4 = line1_1 + line3_3; 43 } 44 45 else if(line2 == "-") 46 { 47 line4_4 = line1_1 - line3_3; 48 } 49 50 else if(line2 == "*") 51 { 52 line4_4 = line1_1* line3_3; 53 } 54 55 else if(line2 == "/") 56 { 57 if(line3_3 != 0) 58 { 59 line4_4 = line1_1 / line3_3; 60 } 61 else 62 { 63 line4_4 = 0; 64 } 65 66 } 67 ui->line4->setText(QString::number(line4_4));//QString::number把整形转化成字符 68 line5 = ui->line4->text(); 69 qDebug()<<line5; 70 }
界面文件如下: