如何删除ok按钮qt c++?



我需要简单的toastr消息,所以我想从QMessageBox中删除ok按钮。

我代码:

QMessageBox* msgbox = new QMessageBox(this);
msgbox->setGeometry(850, 450, 250, 200);
msgbox->setWindowTitle("Error");
msgbox->setText(msg);
msgbox->open();
QTimer* timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), msgbox, SLOT(close()));
QObject::connect(timer, SIGNAL(timeout()), timer, SLOT(stop()));
QObject::connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater()));
timer->start(1000);

试试这个:

auto msgbox = new QMessageBox(this);
msgbox->setGeometry(850, 450, 250, 200);
msgbox->setWindowTitle("Error");
msgbox->setText(msg);
msgbox->setStandardButtons(QMessageBox::NoButton);
msgbox->open();
auto timer = new QTimer(msgbox);
QObject::connect(timer, &QTimer::timeout, msgbox, &QMessageBox::deleteLater);
timer->start(1000);

注意setStandardButtons()的使用,它实际上删除了按钮。但我发现,然后方法close()不工作,所以我不得不用deleteLater()代替它。这也解决了你代码中的错误:你从来没有删除消息框,你只是关闭了它。

我还用新方式取代了旧方式的连接。你永远不应该再使用旧的风格,你应该阻止所有人使用它。新样式的优点在于它允许编译时类型检查。

我还做了一些更改:计时器成为消息框的子节点。然后,它将与消息框一起自动删除。也不需要连接到stop()槽。

PS:我也觉得你滥用QMessageBox的东西,它不是为之设计的。检查QSplashScreen类,也许它更适合你的需要。