1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

QtでLibTorchを使えるようにした

1
Last updated at Posted at 2024-09-07

はじめに

Qt に LibTorch を導入する方法を簡単にまとめておきます。
その際に吐かれたエラーについてもその解決法を記しておきます。

環境

OS : Ubuntu 22.04
Qt : 6.7.2
Qt Creator : 13.0.2


[2025/10/15 追記]

Windows11でも動作確認を行いました。

OS : Windows 11
Qt : 6.10.0
Qt Creator : 15.0.1

Libtorch のダウンロード

下記公式サイトから、欲しいものを選んでダウンロードし、zipファイルを解凍します。
その後、(中に入っている)libtorch ディレクトリを、ホームディレクトリの直下に配置しました。

ホームディレクトリとは、コンピュータのユーザーごとに割り当てられる個人用のディレクトリです。
Windowsであれば、C:\Users\<Your Name> です。

この部分は、他の方が解説してくださっているので省略します。

CMakeLists.txt (LibTorch関連部分のみ抜粋)

LibTorch を使用するために、CMakeLists に追記します。

CMakeLists.txt
set(Torch_DIR $ENV{HOME}/libtorch/share/cmake/Torch)

# --- 中略 ---

find_package(Torch REQUIRED)

# --- 中略 ---

target_link_libraries(MainWindow ${TORCH_LIBRARIES})

[2025/10/15 追記]

Windows の場合、$ENV{HOME} ではなく、$ENV{USERPROFILE}にしてください。

エラー解消

とりあえず、Qt Creator 内で適当に .cpp ファイルを作成し、ビルドしてみます。

Sample.cpp
// LibTorch
#include <torch/torch.h>
#include <torch/script.h>

すると、ivalue_inl.h において、次のようなエラーを吐かれました。

Error
error: expected unqualified-id before ‘)’ token
 1566 |   const std::vector<IValue>& slots() const {
      |                                    ^

原理としては単純で、Qt では slots が予約語になっているので、関数としての slots() を正しく認識できません。

[2026/08/25 追記]
@tom_tom_tom さんより、より良い対処法についてのコメントを頂きました。

手元での動作確認はしていませんが、Using Qt with 3rd Party Signals and Slotsにもそのような記述があるため、この対処法の方が良いと思います。


以下、追記前の対処方法です。

なので、LibTorch のファイルを少し改変します。全部で4か所です。
slots() という名前が悪いだけなので、これを例えば、getSlots() とかにしてあげればよいだけです。

const std::vector<IValue>& getSlots() const {  // Rename

image.png
▲この4か所

エラーが出ている4か所すべてを slots() から getSlots() にします。(4か所で良かった...)


image.png

これで、ビルドすると、ちゃんと通ってくれました。めでたしめでたし。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?