QT中子线程如何使用QMessageBox 代码
时间: 2023-12-04 17:39:03 浏览: 302
QT中,子线程不能直接使用QMessageBox,因为QMessageBox需要在主线程中使用。但是可以通过信号和槽机制来实现子线程中使用QMessageBox的功能。具体步骤如下:
1.在主线程中定义一个槽函数,用于弹出QMessageBox。
```cpp
void MainWindow::showMessageBox(QString title, QString content)
{
QMessageBox::information(NULL, title, content, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
}
```
2.在子线程中定义一个信号,用于触发主线程中的槽函数。
```cpp
signals:
void showMessage(QString title, QString content);
```
3.在子线程中发射信号,触发主线程中的槽函数。
```cpp
emit showMessage("Title", "Content");
```
4.在主线程中连接信号和槽。
```cpp
connect(worker, SIGNAL(showMessage(QString, QString)), this, SLOT(showMessageBox(QString, QString)));
```
其中,worker是子线程的对象,this是主线程的对象。
完整代码如下:
```cpp
// 主线程中定义的槽函数
void MainWindow::showMessageBox(QString title, QString content)
{
QMessageBox::information(NULL, title, content, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
}
// 子线程中定义的信号
signals:
void showMessage(QString title, QString content);
// 子线程中发射信号
emit showMessage("Title", "Content");
// 主线程中连接信号和槽
connect(worker, SIGNAL(showMessage(QString, QString)), this, SLOT(showMessageBox(QString, QString)));
```
阅读全文
相关推荐


















