標准庫STL
Qt VS STL
Qt中的字符串類
——采用Unicode編碼,意味着可以直接支持韓文、日文、中文等等。而STL中的string類不支持Unicode編碼,只支持ascII碼。
——使用隱式共享技術來節省內存和不必要的數據拷貝
——跨平台使用,不必考慮字符串的平台兼容性
注意:隱式共享技術集成了深拷貝和淺拷貝優點於一身的技術。
#include "QCalculatorUI.h" #include <QDebug> QCalculatorUI::QCalculatorUI(): QWidget(NULL,Qt::WindowCloseButtonHint) //此處QCalculatorUI就是作為頂層窗口存在的,雖然這個地方繼承自QWidget,但是賦值為NULL,相當於它是沒有父類的(但是實際上還是有的)。 //將窗口中的最大化和最小化去掉
{ //因為QLineEdit與QCalculatorUI以及QPushButton與QCalculatorUI是組合關系,那么就應該同生死,因此需要在構造函數對其定義。因為此處涉及到在堆上申請內存空間,因此需要 //使用二階構造
} bool QCalculatorUI::construct() { bool ret = true; const char* btnText[20] = { "7", "8", "9", "+", "(", "4", "5", "6", "-", ")", "1", "2", "3", "*", "<-", "0", ".", "=", "/", "C", }; m_edit = new QLineEdit(this); if(m_edit != NULL) { m_edit->move(10,10); m_edit->resize(240,30); m_edit->setReadOnly(true); //使QLineEdit只讀
m_edit->setAlignment(Qt::AlignRight); //使字符串靠右對齊
} else { ret = false; } for(int i=0; (i<4) && ret; i++) { for(int j=0; (j<5) && ret; j++) { if(m_buttons[i*5 + j] != NULL) { m_buttons[i*5 + j] = new QPushButton(this); m_buttons[i*5 + j]->move(10 + (10 + 40)*j, 50 + (10 + 40)*i); m_buttons[i*5 + j]->resize(40,40); m_buttons[i*5 + j]->setText(btnText[i*5 + j]); connect(m_buttons[i*5 + j],SIGNAL(clicked()), this, SLOT(onButtonClicked())); } else { ret = false; } } } return ret; } QCalculatorUI* QCalculatorUI::NewInstance() { QCalculatorUI* ret = new QCalculatorUI(); if((ret == NULL) || !(ret->construct())) { delete ret; ret = NULL; } return ret; } void QCalculatorUI::onButtonClicked() { QPushButton* btn = (QPushButton*)sender(); QString clickText = btn->text(); if(clickText == "<-")//此時應該將字符串的最后一個字符去掉。
{ QString text = m_edit->text(); if(text.length() > 0) { text.remove(text.length()-1,1); m_edit->setText(text); } } else if(clickText == "C") { m_edit->setText( ""); } else if(clickText == "=") { qDebug() << "= symbol:"; } else { m_edit->setText(m_edit->text() + clickText); } } void QCalculatorUI::show() { QWidget::show(); this->setFixedSize(this->width(),this->height()); //固定窗口的大小
} QCalculatorUI::~QCalculatorUI() { }