I am getting a run-time message
QObject: Cannot create children for a parent that is in a different thread.
when starting a QProcess
in a std::thread
. The program runs, but I feel that this message will be trouble, eventually.
I saw this one and this other answers (as well as some in python), which I did not see how to apply to my code.
I am using QtCreator, Qt 6.5 LTS and gcc 11.2.0 in Win10. A minimal working example is below. You will have to create an empty GUI window with QPushButton pushButton
. The class definition is:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void clicked(bool);
private:
Ui::MainWindow *ui;
void launchNotepad();
std::thread th;
QProcess process;
};
And the implementation is:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(clicked(bool)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::clicked(bool)
{
th = std::thread{&MainWindow::launchNotepad,this};
th.detach();
}
void MainWindow::launchNotepad()
{
process.start("notepad");
}
When I click on the button, notepad indeed appears and all looks well. But the Application output console in QtCreator gives me the message “Cannot create children…”. For reasons beyond this question, I do want to work with std::thread
.
My questions:
-
What is the trouble that I am sure eventually I’ll have because of this message ?
-
How to get rid of it, while keeping using
std::thread
?