Subnavigation

Fun with Fonts

From the Cool-Things-That-Are-Surprisingly-Simple-With-Qt category: Download a font from the web and use it right away without saving it to disk or installing it in the system, in 45 lines of code:

#include <QtGui>
#include <QtNetwork>
class CoolTextEdit : public QTextEdit
{
Q_OBJECT
public:
CoolTextEdit(const QUrl &fontUrl);
private slots:
void tryDownloadedFont();
private:
QByteArray downloadedFont;
QHttp *downloader;
};
CoolTextEdit::CoolTextEdit(const QUrl &fontUrl)
{
setPlainText("Please wait while downloading font...");
downloader = new QHttp(this);
connect(downloader, SIGNAL(done(bool)), this, SLOT(tryDownloadedFont()));
QBuffer *buffer = new QBuffer(&downloadedFont, downloader);
downloader->setHost(fontUrl.host());
downloader->get(fontUrl.path(), buffer);
}
void CoolTextEdit::tryDownloadedFont()
{
downloader->deleteLater();
downloader = 0;
int id = QFontDatabase::addApplicationFontFromData(downloadedFont);
if (id < 0) {
setPlainText("Loading the font failed :(");
return;
}
QFont f(QFontDatabase::applicationFontFamilies(id).first());
f.setPointSize(48);
setFont(f);
setPlainText(f.family());
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
CoolTextEdit edit(QUrl("http://fonts.tom7.com/f/actionj.ttf"));
edit.resize(400, 200);
edit.show();
return app.exec();
}
#include "main.moc"

Save as main.cpp, qmake -project QT+=network, qmake, (n)make and run :)
Here's the obligatory screenshot:
Screenshot


Blog Topics:

Comments