This is a small gift made for my girlfriend's birthday. My girlfriend is clamoring every day to tell a joke to her. Now, let's make a joke software for her. However, women, emotional animals, still like what you say!
Bytes ----------------------------------------------------------------------------------------------------------------
All source code can be downloaded through https://github.com/bobosp/joke.
Bytes ----------------------------------------------------------------------------------------------------------------
Take over the previous two articles:
Http://blog.csdn.net/teamossp/article/details/8912789
Http://blog.csdn.net/teamossp/article/details/8918996
This is a summary of this program.
The following is a part of the code to explain your understanding of the qt api and some low-level errors in C ++:
1. New and delete.
InternetJoke::InternetJoke(QWidget *parent) : QDialog(parent), joke(new QString), networkAccess(new QNetworkAccessManager(this)), url(new QString("http://www.jokearea.com/")), codec(QTextCodec::codecForName("U-TF8")){ requestHttp (); connect(networkAccess,SIGNAL(finished(QNetworkReply*)) ,this,SLOT(showHttp(QNetworkReply*)));}
Class member pointer, use new to initialize a pointer, so this is created by the programmer on the stack, and must be deleted at last, usually in the destructor, otherwise it will cause memory leakage,
If it is a local pointer of new in a function, manual delete is also required, which is different from an object defined in the function:
QTextStream textReader(reply);
This is on the stack, and the memory will be automatically reclaimed after the function is completed.
2. QT displays Chinese Characters
Generally, you need to add the following code to the main function,
Qtextcodec: setcodecfortr (qtextcodec: codecforname ("UTF-8"); qtextcodec: equals (qtextcodec: codecforname ("UTF-8"); qtextcodec: equals (qtextcodec :: codecforname ("UTF-8"); // The button displays Chinese characters without garbled characters
For classes that contain Chinese strings, set textcodec:
Qtextstream textreader (& xmlfile); qtextcodec * codec = qtextcodec: codecforname ("UTF-8"); textreader. setcodec (codec); // convert to display Chinese
3. Http retrieval steps
URL (New qstring ("http://www.jokearea.com/"), // initialize networkaccess-> get (qnetworkrequest (qurl (* URL); Connect (networkaccess, signal (finished (qnetworkreply *), this, slot (showhttp (qnetworkreply *); void class: showhttp (qnetworkreply * reply); // slot function for processing HTTP files