Qt諾基亞官方中文教程L3_Qt的數據類型機會及.ppt_第1頁
Qt諾基亞官方中文教程L3_Qt的數據類型機會及.ppt_第2頁
Qt諾基亞官方中文教程L3_Qt的數據類型機會及.ppt_第3頁
Qt諾基亞官方中文教程L3_Qt的數據類型機會及.ppt_第4頁
Qt諾基亞官方中文教程L3_Qt的數據類型機會及.ppt_第5頁
已閱讀5頁,還剩60頁未讀 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、.,數據類型 集合和文 件,Qt in Education,This work is a Chinese translation of the original Qt Educational Training Materials published by Nokia: 2010 Nokia Corporation and its Subsidiary(-ies). Nokia, Qt and the Nokia and Qt logos are the registered trademarks of Nokia Corporation in Finland and other countri

2、es worldwide. This translation was created by Communication and Computer Network Laboratory of Guangdong Province, South China University of Technology. 2010 Communication and Computer Network Laboratory of Guangdong Province, South China University of Technology. The enclosed Qt Educational Trainin

3、g Materials are provided under the Creative Commons Attribution-Non-Commercial-Share Alike 2.5 License Agreement. The full license text is available here: /licenses/by-nc-sa/2.5/legalcode.,此文檔內容是由諾基亞公司發(fā)布的原創(chuàng)Qt教育培訓文檔的中文翻譯: 2010諾基亞公司及其附屬公司。 Nokia (諾基亞),Qt以及Nokia與Qt商標是Nokia公司在芬蘭

4、和全球其他國家的注冊商標。 該翻譯版本由 華南理工大學廣東省計算機網絡重點實驗室 創(chuàng)造。 2010 華南理工大學廣東省計算機網絡重點實驗室 本Qt 教育培訓材料依照署名-非商業(yè)性使用-相同方式共享 2.5許可協議(Creative Commons Attribution-Non-Commercial-Share Alike 2.5 License Agreement)發(fā)布。 完整的許可證文本可以在這里找到:/licenses/by-nc-sa/2.5/legalcode。,管理文本,簡單的C字符串是方便的,但這僅限于本地字符編碼 QString

5、類試圖成為現代的字符串類 Unicode 和 codecs 隱式共享的性能,char *text = Hello world!;,QString,支持存儲Unicode字符串,幾乎當前在用的所有書寫系統都能表示 支持從不同的本地編碼轉換或者轉成不同的本地編碼 提供了一個方便的字符串檢查和修改的API,QString:toAscii QString:toLatin1 QString:toLocal8Bit,建立字符串,有三種建立字符串的主要方法 運算符+ 方法 QStringBuilder 的方法 arg 方法,QString res = QString(Hello %1, the value

6、is %2) .arg(name) .arg(42);,QString res = Hello “ + name + “, the value is + QString:number(42);,QString res = Hello “ % name % “, the value is % QString:number(42);,QStringBuilder,使用+運算符來連接字符串,這需要多次內存分配和字符串長度檢查 一個更好的方式是包含QStringBuilder并使用操作符 該字符串生成器在連接之前一次性收集所有字符串的長度,只需執(zhí)行一次內存分配,QString res = Hello

7、“ % name % “, the value is % % QString:number(42);,QString temp = Hello “; temp = temp % name; temp = temp % “, the value is % temp = temp % QString:number(42);,QString:arg,arg方法用值來替換 %1-99 可以處理字符串,字符,整型和浮點型 能在數字基數之間轉換,%1 + %2 = %3, the sum is %3,.).arg(value, width, base, fillChar); .).arg(42, 3, 1

8、6, QChar(0); / Results in 02a,.).arg(QString, . QString) .).arg(int a) .).arg(uint a) .).arg(long a) .).arg(ulong a) .).arg(qlonglong a),.).arg(qulonglong a) .).arg(short a) .).arg(ushort a) .).arg(QChar a) .).arg(char a) .).arg(double a),子串,使用left, right 和 mid訪問子串 如果mid不指定長度,則返回字符串的剩余部分 用 replace查找

9、和替代字符串,QString s = Hello world!; r = s.left(5); / Hello r = s.right(1); / ! r = s.mid(6,5); / world,r = s.mid(6); / world!,r = s.replace(world, universe); / Hello universe!,打印到控制臺,Qt是一個主要用于可視應用的工具包,即不專注于命令行界面的 要打印, 用 qDebug 函數 它總是可用, 但是在建立發(fā)布版本時會靜默 像printf 函數那樣工作 (但加上 “n”) 使用qPrintable宏很容易打印QString的文

10、本 當包含QtDebug后,能與流操作符一起使用,qDebug(Integer value: %d, 42); qDebug(String value: %s, qPrintable(myQString);,#include qDebug() Integer value: 42; qDebug() String value: myQString; qDebug() Complex value: myQColor;,與數字間轉換,把數字轉換為字符串 把字符串轉換為數值,QString:number(int value, int base=10); QString twelve = QString

11、:number(12); / 12 QString oneTwo = QString:number(0 x12, 16); / 12 QString:number(double value, char format=g, int precision=6); QString piAuto = QString:number(M_PI); / 3.14159 QString piScientific = QString:number(M_PI,e); / 3.141593e+00 QString piFixedDecimal = QString:number(M_PI,f,2); / 3.14,bo

12、ol ok; QString i = 12; int value = i.toInt( if(ok) / Converted ok ,bool ok; QString d = 12.36e-2; double value = d.toDouble( if(ok) / Converted ok ,與std:(w)string一起工作,當連接第三方庫和其他代碼時,與標準庫的字符串轉換很方便 從標準庫的字串轉換成其他 轉成標準庫字符串,QString qs = Hello world!; std:string ss = qs.toStdString(); std:wstring sws = qs.t

13、oStdWString();,std:string ss = Hello world!; std:wstring sws = Hello world!; QString qss = QString:fromStdString(ss); QString qsws = QString:fromStdWString(sws);,Empty字符串和null字符串,一個QString可以為null, 即什么也沒有包含 它也可是empty,即包含 一個空字符串,QString e = ; e.isNull(); / false e.isEmpty(); / true,QString n = QString

14、(); n.isNull(); / true n.isEmpty(); / true,分割和組合,一個QString 能夠被分割成子串 由此產生的對象是QstringList,它可被組合成一個QString,QString whole = Stockholm - Copenhagen - Oslo - Helsinki; QStringList parts = whole.split( - );,QString wholeAgain = parts.join(, ); / Results in Stockholm, Copenhagen, Oslo, Helsinki,QStringList,

15、QStringList是一個專門列表類型 為存儲字符串而設計 提供了一個方便的作用于列表中字符串的API 這個類使用隱含共享 副本修改 作為const引用傳遞的代價低,建立和修改字符串列表,用 操作符把字符串增加到字符串列表 replaceInStrings函數能讓你在QStringList的所有字符串中進行搜索和替換。,QStringList verbs; verbs = running walking compiling linking;,qDebug() verbs; / (running, walking, compiling, linking) verbs.replaceInStri

16、ngs(ing, er); qDebug() verbs; / (runner, walker, compiler, linker),排序與篩選,QStringList可以進行排序. .篩選. .及清除重復的條目,qDebug() capitals; / (Stockholm, Oslo, Helsinki, Copenhagen) capitals.sort(); qDebug() capitals; / (Copenhagen, Helsinki, Oslo, Stockholm),QStringList capitalsWithO = capitals.filter(o); qDebug

17、() capitalsWithO; / (Copenhagen, Oslo, Stockholm),capitals capitalsWithO; qDebug() capitals; / (Copenhagen, Helsinki, Oslo, Stockholm, / Copenhagen, Oslo, Stockholm) capitals.removeDuplicates(); qDebug() capitals; / (Copenhagen, Helsinki, Oslo, Stockholm),遍歷字符串,使用操作符 和 length 函數,你可以遍歷QStringList的內容

18、另一種方法是使用at() 函數,它提供列表項的只讀訪問 你也可以使用foreach 宏,QStringList capitals; for(int i=0; icapitals.length(); +i) qDebug() capitalsi;,QStringList capitals; foreach(const QString ,Qt的集合,QStringList接口不是唯一的字符串列表。 QStringList是由QList 派生的。 QList是眾多Qt容器模板類中的一個 QLinkedList - 在中間快速插入,通過迭代器 QVector - 使用連續(xù)內存,緩慢插入 QStack

19、LIFO, 后進先出 QQueue FIFO, 先進先出 QSet 唯一值 QMap 關聯數組 QHash 關聯數組,比QMap快,但需要哈希 QMultiMap 通過每個鍵的多個值關聯數組 QMultiHash 通過每個鍵的多個值關聯數組,填充,你可以用操作符填充一個QList 函數prepend, insert 和append 也可以使用,QList fibonacci; fibonacci 0 1 1 2 3 5 8;,list.append(4);,QList list; list.append(2);,list.prepend(1);,list.insert(1,3);,index

20、0: 2,index 0: 2,index 1: 4,index 0: 1,index 1: 2,index 2: 3,index 0: 2,index 1: 3,index 2: 4,index 3: 4,刪除,使用removeFirst,removeAt,removeLast從Qlist中刪除列表項 用takeFirst, takeAt, takeLast去得到一個列表項 使用removeAll或removeOne刪除特定值的列表項,while(list.length() list.removeFirst();,QList widgets; widgets new QWidget new

21、QWidget; while(widgets.length() delete widgets.takeFirst();,QList list; list 1 2 3 1 2 3; list.removeAll(2); / Leaves 1, 3, 1, 3,訪問,一個QList 的索引范圍是0 -(length-1) 單個列表項可以用at 或者 操作符來訪問。如果你能接受超出界限的情況,可以用value。 運算符返回一個可修改的引用,for(int i=0; ilist.length(); +i) listi+;,for(int i=0; ilist.length(); +i) qDebug(

22、At: %d, : %d, list.at(i), listi); for(int i=0; i100; +i) qDebug(“Value: %d”, list.value(i);,迭代 - Java風格,Qt 支持 Java 風格迭代器 Java風格的迭代器指向條目之間 toFront把迭代器置于第一項 前面 toBack把迭代器置于最后一 項后面 用peekNext和peekPrevious 參考列表項 用 next 或 previous指向列表項,item 1,item 5,item 4,item 3,item 2,i.toBack(),i.toFront(),i.peekNext()

23、 i.next(),i.peekPrevious() i.previous(),i,QListIterator iter(list); while(iter.hasNext() qDebug(Item: %d, iter.next();,迭代 - STL的風格,Qt 支持 STL 風格的迭代器 STL的迭代器指向每個列表項,并以此作為結束標記無效項 第一項用begin來返回 結束標志用end返回 * 操作符關聯項的值 當你向后遍歷訪問之前, 必須移動操作符,item 1,item 5,item 4,item 3,item 2,begin(),i,end(),end(),*i,for(QList

24、:ConstIterator iter=list.begin(); iter!=list.end(); +iter) qDebug(Item: %d, *iter);,懶惰式的迭代,遍歷整個集合,使用foreach 警告!當按值返回時要確保復制列表,QStringList texts; foreach(QString text, texts) doSomething(text);,QStringList texts; foreach(const QString ,const QList sizes = splitter-sizes(); QList:const_iterator i; for(

25、i=sizes.begin(); i!=sizes.end(); +i) processSize(*i);,與STL的交互,QList 能與相應的std:list相互轉換 與STL的相互轉換意味著對列表內容進行深度復制 不存在隱含共享,QList list; list stlList = list.toStdList(); QList otherList = QList:fromStdList(stlList);,其他集合,誰能代替QList,它們跟QList有何區(qū)別? QLinkedList 用索引訪問緩慢 使用迭代器很快 快速(恒定時間)在列表的中間插入 QVector 使用連續(xù)的內存空間

26、 插入和置首緩慢,其他集合,注意,攤銷行為(amortized behavior)是指在實時環(huán)境中不可預知的次數 其他集合是以Qlist為基礎的 QStringList QStack QQueue QSet,特殊情況 - QStack,堆,一個后進先出(LIFO)的容器 后進先出 列表項壓入堆 列表項彈出堆 用top()取出頂項,s.push(),s.pop(),QStack stack; stack.push(1); stack.push(2); stack.push(3); qDebug(Top: %d, stack.top(); / 3 qDebug(Pop: %d, stack.pop

27、(); / 3 qDebug(Pop: %d, stack.pop(); / 2 qDebug(Pop: %d, stack.pop(); / 1 qDebug(isEmpty? %s, stack.isEmpty()?yes:no);,特殊情況- QQueue,隊列,一個先進先出( FIFO)的 容器先進先出 項排隊進入隊列 項從隊列中出列 取第一項可以用head(),s.enqueue(),s.dequeue(),QQueue queue; queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); qDebug(Head: %d, queu

28、e.head(); / 1 qDebug(Pop: %d, queue.dequeue(); / 1 qDebug(Pop: %d, queue.dequeue(); / 2 qDebug(Pop: %d, queue.dequeue(); / 3 qDebug(isEmpty? %s, queue.isEmpty()?yes:no);,特殊情況- QSet,一個集合包含值,但對每個值只有一個實例。 可以判斷一個值是否是集合的一部分 也可以遍歷一個集合,看到所有的值 可以轉換一個QList 到一個QSet,QSet primes; primes 2 3 5 7 11 13; for(int i

29、=1; i=10; +i) qDebug(%d is %sprime, i, primes.contains(i)?:not );,foreach(int prime, primes) qDebug(Prime: %d, prime);,QList list; list set = list.toSet(); qDebug() list; / (1, 1, 2, 2, 2, 3, 3, 5) qDebug() set; / (1, 2, 3, 5),鍵 - 值集合,QMap和QHash類讓你創(chuàng)建關聯數組,QHash hash; hashHelsinki = 1310755; hashOslo

30、= 1403268; hashCopenhagen = 1892233; hashStockholm = 2011047; foreach(const QString ,QMap map; mapHelsinki = 1310755; mapOslo = 1403268; mapCopenhagen = 1892233; mapStockholm = 2011047; foreach(const QString ,使用QMap,QMap 類需要操作符 來定義關鍵類型 此操作符用來保持鍵的順序 填充使用運算符或 insert來完成 對于讀取,用value 結合contains,if(map.co

31、ntains(Oslo) qDebug(Oslo: %d, map.value(Oslo); qDebug(Berlin: %d, map.value(Berlin,42);,mapStockholm = 2011047; map.insert(London, 13945000);,哈希,QMap使用了給定的模板中的類型的鍵 QHash 使用 uint 值 key類型散列到一個uint值 運用uint 值可能提高性能 哈希值表示鍵沒有排序 哈希函數必須設法避免碰撞,以達到良好的性能,使用 QHash,鍵類型必須提供一個qHash 函數和操作符= 到QHash 相對Qmap,填充和讀取相同,ui

32、nt qHash(const Person ,一鍵多值,QMultiMap和QMultiHash提供支持一鍵多值的關聯數組,QMultiMap multiMap; multiMap.insert(primes, 2); multiMap.insert(primes, 3); multiMap.insert(primes, 5); . multiMap.insert(fibonacci, 8); multiMap.insert(fibonacci, 13); foreach(const QString ,休息,Qt的類型定義,C + +中沒有定義嚴格跨平臺類型的大小 sizeof(int) =

33、? 對于跨平臺的代碼,以嚴格的方式定義的所有類型是很重要的,ARM = 4 bytes x86 = 4 bytes IA64 = 8 bytes .,跨平臺類型,所有類型都定義在頭中,Qt的復雜類型,Qt提供了多個復雜的類和類型,QColor,QBrush,QRect,QPoint,QString,QSize,QList,QImage,QByteArray,QPixmap,QPen,QFont,QVariant,有時候,希望能夠通過一個普通的接口返回任何類型 QVariant類可以被視為一個聯合 創(chuàng)造一個Qt的類型聯合是不可能,因為聯合需要默認的構造函數 變異類可以包含自定義的復雜類型,例如Q

34、Color屬于QtGui,QVariant屬于QtCore 一旦它們被聲明,聯合就不能擴展到更多類型,const QVariant ,使用QVariant,基本類型用構造函數和 toType 函數處理 非QtCore類型,如自定義類型,使用setValue 函數和模板 value 函數來處理,QVariant v; QColor c(Qt:red); qDebug() (); / After: QColor(ARGB 1, 1, 0, 0) qDebug() After: c;,QVariant v; int i = 42; qDebug() Before: i; / Before: 42 v

35、 = i; i = v.toInt(); qDebug() After: i; / After: 42,自定義的復雜類型,我們實現一個小類,包含一個人的名字和年齡,class Person public: Person(); Person(const Person ,Person:Person() : m_age(-1) . void Person:setAge(int a) m_age = a; bool Person:isValid() const return (m_age = 0); ,QVariant與Person對象,試圖通過一個QVariant對象傳遞一個Person對象失敗 在

36、元類型系統中聲明這一類型解決了問題,class Person . ; Q_DECLARE_METATYPE(Person) #endif / PERSON_H,qmetatype.h:200: error: qt_metatype_id is not a member of QMetaTypeId,QVariant與Person對象,當類型注冊成為一個元類型, Qt能把它存儲在一個Qvariant中 要求聲明類型 Public default constructor Public copy constructor Public destructor,QVariant var; var.setV

37、alue(Person(Ole, 42); Person p = var.value(); qDebug(%s, %d, qPrintable((), p.age();,然后,它中斷了.,當與信號和槽工作,大部分連接是直接的 直接連接時,類型可工作 排隊的連接,即非阻塞,異步的時候,這些類型不能工作(比如跨越線程邊界),connect(src, SIGNAL(), dest, SLOT(), Qt:QueuedConnection); . QObject:connect: Cannot queue arguments of type Person (Make sure Person

38、 is registered using qRegisterMetaType().),注冊類型,錯誤信息告訴我們如何解決問題 qRegisterMetaType函數必須在連接建立之前被調用 (通常從main開始),int main(int argc, char *argv) qRegisterMetaType(); .,文件和文件系統,在跨平臺中的文件和目錄帶來許多問題 系統是否有驅動器,或只是一個根? 路徑是否被“/” 或 “”隔開? 系統在哪里存儲臨時文件? 用戶在哪里存儲文檔? 應用程序在哪里存儲?,路徑,用QDir 類去處理路徑 學會用靜態(tài)函數去初始化,QDir d = QDir:ro

39、ot(); / C:/ on windows QDir:current() / Current directory QDir:home() / Home directory QDir:temp() / Temporary directory / Executable directory path QDir(QApplication:applicationDirPath(),QDir d = QDir(C:);,找目錄內容,entryInfoList返回該目錄內容的信息列表 你可以添加過濾器以跳過文件或目錄,QFientryInfoListleInfoList infos = QDir:root

40、().entryInfoList(); foreach(const QFileInfo ,QDir:Dirs QDir:Files QDir:NoSymLinks QDir:Readable QDir:Writable QDir:Executable QDir:Hidden QDir:System,找目錄內容,QDir:Name QDir:Time QDir:Size QDir:Type QDir:DirsFirst QDir:DirsLast QDir:Reversed,QFileInfoList infos = QDir:root().entryInfoList(QDir:Dirs, QD

41、ir:Name); foreach(const QFileInfo ,你也可以指定排序順序 從主目錄根據名字排列所有目錄,找目錄內容,最后,可以添加名字過濾器,QFileInfoList infos = dir.entryInfoList(QStringList() *.cpp *.h, QDir:Files, QDir:Name); foreach(const QFileInfo ,QFileInfo,每個 QFileInfo 對象都有許多函數 absoluteFilePath 某項的完整路徑 isDir / isFile / isRoot 項的類型 isWriteable / isRead

42、able / isExecutable 文件的權限,/home/john/the-archive.tar.gz,fileName,absolutePath path,baseName,completeSuffix,suffix,打開和讀取文件,QFile 用來訪問文件,QFile f(/home/john/input.txt); if (!f.open(QIODevice:ReadOnly) qFatal(Could not open file);,while(!f.atEnd() QByteArray data = f.read(160); processData(data); ,QByte

43、Array data = f.readAll(); processData(data);,f.close();,寫文件,QFile f(/home/john/input.txt); if (!f.open(QIODevice:WriteOnly) qFatal(Could not open file); QByteArray data = createData(); f.write(data); f.close();,寫入文件時,用WriteOnly 模式打開文件,用寫函數向文件添加數據 文件也可用ReadWrite 模式打開 Append或Truncate標志可以與寫入模式相結合以追加數據到

44、文件或截斷它(即清除文件以前的內容),if (!f.open(QIODevice:WriteOnly|QIODevice:Append),QIODevice,QFile由QIODevice派生 構造函數QTextStream和QDataStream以QIODevice指針為參數,而不是QFile指針 QIODevice的實現 QBuffer 讀寫到內存緩沖 區(qū) QextSerialPort 串行(RS232) 通訊 (第三方) QAbstractSocket - TCP,SSL和UDP套接字類的基 QProcess 讀寫進程的標準輸入和輸出,流操作與文件,讀取和寫入函數在許多情況下顯得尷尬 如處理復雜類型等 一個現代的方案是使用流操作 Qt的提供兩種流操作 用于處理文本文件 用于處理二進制文件格式,QT

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論