How to Create Torrent Files with qBittorrent: GUI, C++, and API Methods
qBittorrent creates torrent files through a multi-threaded architecture where the TorrentCreatorDialog collects user input, the TorrentCreator class (a QRunnable task) performs the heavy lifting in background threads, and the Web API exposes the same functionality via HTTP POST requests to /api/v2/torrents/create.
The qbittorrent/qBittorrent repository provides three distinct ways to generate .torrent metadata files: through the desktop client’s interface, programmatically via C++ using the core library classes, or remotely through the built-in Web API. Each method relies on the same underlying infrastructure defined in src/base/bittorrent/torrentcreator.h and src/base/bittorrent/torrentcreator.cpp.
Architecture Overview: How qBittorrent Creates Torrents
The torrent creation workflow follows a strict separation between the user interface and core logic to keep the application responsive:
- Entry Point: The
MainWindowclass insrc/gui/mainwindow.cpp(line 1254) instantiatesTorrentCreatorDialogwhen the user selects File → Create Torrent... - Parameter Collection: The dialog populates a
BitTorrent::TorrentCreatorParamsstruct with the source path, piece size, private flag, trackers, web seeds, comment, and alignment settings. - Piece Calculation: Clicking "Calculate total pieces" spawns a
PieceCalculationThreadthat invokes the static methodBitTorrent::TorrentCreator::calculateTotalPiecesto preview the piece count without blocking the main thread. - Background Processing: When the user confirms, the dialog constructs a
BitTorrent::TorrentCreatorobject (which inherits fromQRunnable) and submits it to aQThreadPoolviam_threadPool.start(torrentCreator). - Signal-Based Updates: The creator emits
progressUpdated,creationSuccess, andcreationFailuresignals, which the dialog handles viaupdateProgressBar,handleCreationSuccess, andhandleCreationFailureslots. - Post-Creation Seeding: On success,
handleCreationSuccessreads theTorrentCreatorResult, builds anAddTorrentParamsstructure, and asks the globalBitTorrent::Sessionsingleton to add the torrent to the transfer list if "Start seeding" is enabled.
Method 1: Creating Torrent Files Using the GUI
To create a torrent interactively:
- Open qBittorrent and choose File → Create Torrent... (or click the toolbar button). This action is defined in
src/gui/mainwindow.cppat line 1254. - In the TorrentCreatorDialog, select the file or folder you want to share.
- Choose a piece size or leave it on "Auto" (mapped to
pieceSize = 0inTorrentCreatorParams). - Enter tracker URLs (one per line) and optional web seeds.
- Toggle private, add a comment, or specify a source string as needed.
- Click Calculate total pieces to preview the piece count via
PieceCalculationThread. - Click Create Torrent, choose the destination path for the
.torrentfile, and confirm. - Check Start seeding to have
BitTorrent::Sessionautomatically add the torrent to your transfer list immediately after generation.
Method 2: Creating Torrents Programmatically with C++
You can invoke the same logic from custom plugins or Qt applications by using the core classes directly:
#include <base/bittorrent/torrentcreator.h>
#include <base/bittorrent/torrentcreationtask.h>
#include <base/bittorrent/torrentcreationmanager.h>
#include <base/path.h>
using namespace BitTorrent;
// 1. Fill the parameters
TorrentCreatorParams params;
params.sourcePath = Path(u"/home/user/my_folder"); // file or directory
params.torrentFilePath = Path(u"/home/user/my_folder.torrent"); // where to write the .torrent
params.pieceSize = 0; // 0 → auto (Qt UI uses "Auto")
params.isPrivate = false;
params.trackers = {u"udp://tracker.openbittorrent.com:80/announce"};
params.urlSeeds = {}; // optional web seeds
params.comment = u"This is a demo torrent";
params.source = u"qBittorrent demo";
// 2. Create the creator object (QRunnable)
auto *creator = new TorrentCreator(params);
// 3. Connect to signals (optional – for progress feedback)
QObject::connect(creator, &TorrentCreator::progressUpdated,
[](int perc) { qDebug() << "Progress:" << perc << "%"; });
QObject::connect(creator, &TorrentCreator::creationSuccess,
[](const TorrentCreatorResult &res) {
qDebug() << "Torrent created at:" << res.torrentFilePath;
});
QObject::connect(creator, &TorrentCreator::creationFailure,
[](const QString &msg) { qWarning() << "Failed:" << msg; });
// 4. Run it in a thread pool (the same pool used by the UI)
static QThreadPool pool;
pool.start(creator); // `creator` will delete itself after finishing
Explanation: The TorrentCreatorParams struct mirrors exactly what the GUI gathers. Because TorrentCreator implements QRunnable::run(), submitting it to a QThreadPool prevents UI blocking. The creator writes the final .torrent file to params.torrentFilePath and emits creationSuccess containing a TorrentCreatorResult struct with the final path, save directory, and piece size used.
Method 3: Creating Torrents via the Web API
The embedded Web UI exposes torrent creation through a REST endpoint. Send a POST request to:
POST /api/v2/torrents/create
Include form fields matching TorrentCreatorParams such as savepath, url, trackers, comment, private, and piece_size. The implementation resides in src/webui/api/torrentcreatorcontroller.cpp, which validates the input, constructs a TorrentCreatorParams object, and delegates to the same TorrentCreator class used by the desktop GUI.
Key Classes and Source Files
| Class | Purpose | File |
|---|---|---|
| TorrentCreatorDialog | UI widget that gathers user input and orchestrates the creation job. | src/gui/torrentcreatordialog.hsrc/gui/torrentcreatordialog.cpp |
| TorrentCreator | Core logic that generates the .torrent file using libtorrent; implements QRunnable for thread-pool execution. |
src/base/bittorrent/torrentcreator.hsrc/base/bittorrent/torrentcreator.cpp |
| TorrentCreatorParams | Plain-old-data struct holding all creation options (paths, trackers, flags). | src/base/bittorrent/torrentcreator.h |
| TorrentCreatorResult | Struct returned on success containing the final torrent path and metadata. | src/base/bittorrent/torrentcreator.h |
| TorrentCreatorController | Web API handler that exposes creation via HTTP. | src/webui/api/torrentcreatorcontroller.hsrc/webui/api/torrentcreatorcontroller.cpp |
| Session | Global singleton that handles post-creation seeding when requested. | src/base/bittorrent/session.h |
Summary
- Launch the dialog via
MainWindowat line 1254 insrc/gui/mainwindow.cppto trigger the GUI workflow. - Background execution is handled by submitting a
TorrentCreatorinstance toQThreadPool, preventing interface freezes. - Configure parameters using the
TorrentCreatorParamsstruct and preview piece counts withTorrentCreator::calculateTotalPieces. - Enable immediate seeding by having
BitTorrent::Sessionprocess the result afterhandleCreationSuccessemits. - Automate via API using the
/api/v2/torrents/createendpoint implemented insrc/webui/api/torrentcreatorcontroller.cpp.
Frequently Asked Questions
How do I calculate the total number of pieces before creating the torrent?
The GUI spawns a PieceCalculationThread that calls the static method BitTorrent::TorrentCreator::calculateTotalPieces defined in src/base/bittorrent/torrentcreator.cpp. This runs the same sizing algorithm used during actual creation to preview how many pieces will be generated based on your content size and selected piece size.
Can I start seeding immediately after creating a torrent file?
Yes. When TorrentCreator emits the creationSuccess signal, the dialog’s handleCreationSuccess slot (in src/gui/torrentcreatordialog.cpp) reads the TorrentCreatorResult, constructs an AddTorrentParams object, and passes it to the global BitTorrent::Session singleton. Enable the "Start seeding" checkbox in the GUI or set the equivalent flag in the API request.
Is it possible to create torrents from the command line?
While qBittorrent is primarily a GUI application, you can automate creation via the Web API by sending a POST request to /api/v2/torrents/create with URL-encoded parameters matching TorrentCreatorParams. Alternatively, link against the qBittorrent base library and use the C++ snippet above in your own Qt-based CLI tool.
What parameters can I configure when creating a torrent?
The TorrentCreatorParams struct in src/base/bittorrent/torrentcreator.h exposes: sourcePath (file or folder), torrentFilePath (destination), pieceSize (0 for auto), isPrivate (boolean), trackers (list of URLs), urlSeeds (web seeds), comment, source, and alignment options. These map directly to the input fields in the TorrentCreatorDialog.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →