Qt とは?
Qt (キュート) はC++ でGUI アプリケーションを作ることができる言語.
読み方は正式にはキュートらしい, キューティーではない.
Windows, Mac, Linux などOS 問わず実行できるのが魅力的.
ちなみにPython で動かせるPyQt なんかもある.
ここでは普通のQt で色々とまとめていこうと思う.
環境
ここではMac での環境でやっていく.
- Mac OS Monterey (12.4_
- M1 チップ
Qt のインストール
いつもどおりHomebrew を使ってインストールしましょう.
$ brew install qt
2023 年1 月11 日時点では, 6.4.2 バージョンがインストールされた.
続いてPATH を通しておこう.
以下ではbash_profile に書き込んでるが,
zsh に通すならそちらで.
$ cd
$ export PATH="/usr/local/opt/qt/bin:$PATH" >> .bash_profile
端末を再起動させるか, bash_profile なり, zsh を実行する.
$ . .bash_profile
Hello World!
Qt の練習用にQt ディレクトリなどを作っておこう.
$ cd
$ mkdir Qt
さらにHello ディレクトリでも作っておく.
$ cd Qt
$ mkdir Hello
このディレクトリに適当なエディタで以下のようなHello.cpp ファイルを作る.
#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QLabel *label = new QLabel("Hello World!");
label->show();
return app.exec();
}
コンパイルする.
$ qmake -project
すると, 同じディレクトリにHello.pro というファイルができる.
このファイルに以下のように
QT+=widgets を最終行に書き込んでおく.
######################################################################
# Automatically generated by qmake (3.1) Wed Jan 11 14:21:25 2023
######################################################################
TEMPLATE = app
TARGET = hello
INCLUDEPATH += .
# You can make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# Please consult the documentation of the deprecated API in order to know
# how to port your code away from it.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
# Input
SOURCES += hello.cpp
QT+=widgets
続いて, Hello.pro をqmake した後で, make してビルドする.
$ qmake Hello.pro
$ make
エラーなどが起きていなければ, Hello.app というディレクトリができており, このディレクトリの中身にあるファイルを実行する.
./Hello.app/Contents/MacOS/Hello
HTML 形式で文字を装飾
Qt では文字の装飾はHTML 形式でできる.
フォントサイズを大きくして,
Hello の部分をイタリックに, World! の部分を赤文字にしてみる.
書き換えるのはHello.cpp のlabel 変数をの部分を変える.
#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
- QLabel *label = new QLabel("Hello World!");
+ QLabel *label = new QLabel("<h2><i>Hello</i>" " <font color = red>World!</font></h2>");
label->show();
return app.exec();
}
qmake -project からビルドし直して, 実行すると以下のようにフォントスタイルを変えたウィンドウが現れる.
ひとまずここまで
まだまだGUIとは言えないけれど,備忘録も兼ねながらどんどんまとめていきたい.
ひとまず自分がやりたいことは測定装置とシリアル通信して, それらの制御なんかをGUI でできるようにしたい. LabVIEW なんかを使えばできるけど, Qt だったら無料でできるので...