自动关闭QMessageBox

时间:2010-02-10 12:44:35

标签: qt qmessagebox

我正在构建一个Qt Symbian项目,我想向用户显示应在几秒钟后自动关闭的通知。我看到诺基亚在他们的ui中使用了很多。

现在我正在使用下面的代码,以便用户可以关闭QMessageBox,但如果可以在1或2秒后自动关闭QMessageBox,我希望如此。我怎么能用Qt做到这一点?

QMessageBox msgBox;
msgBox.setText("Hello!");
msgBox.setIcon(QMessageBox::Information);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();

5 个答案:

答案 0 :(得分:7)

非常感谢!我的解决方案:

我创建了自己的类(MessageBox)这是我展示它的代码:

MessageBox msgBox;
msgBox.setText("Hello!");
msgBox.setIcon(QMessageBox::Information);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setAutoClose(true);
msgBox.setTimeout(3); //Closes after three seconds
msgBox.exec();

这是我的班级:

class MessageBox : public QMessageBox

int timeout;
bool autoClose;
int currentTime;

void MessageBox::showEvent ( QShowEvent * event ) {
    currentTime = 0;
    if (autoClose) {
    this->startTimer(1000);
    }
}

void MessageBox::timerEvent(QTimerEvent *event)
{
    currentTime++;
    if (currentTime>=timeout) {
    this->done(0);
    }
}

答案 1 :(得分:4)

我建议继承QMessageBox以添加您自己想要的行为......

当启用AutoClose选项时,添加setAutoClose(bool)setAutoCloseTimeout(int)等方法并在QTimer上触发showEvent会很有趣!

通过这种方式,您甚至可以改变QMessageBox的外观,并在文本中说“此框会在XXX秒后自动关闭......”或进度条等等......

答案 2 :(得分:2)

相反,您可以使用Singleshot计时器轻松关闭任何对话框或QLabel

QTimer *timer;
QTimer::singleShot(10000, msgBox, SLOT(close()));

答案 3 :(得分:1)

使用此代码:

QTimer *timer;
QTimer::singleShot(10000, msgBox, SLOT(close()));

你得到:

QObject::connect: Incompatible sender/receiver arguments
        QTimer::timeout() --> QMessageBox::

Becouse msgBOx(接收者)必须是QtCore对象..和QMessageBox继承QtGui。见https://srinikom.github.io/pyside-docs/PySide/QtCore/QTimer.html#PySide.QtCore.PySide.QtCore.QTimer.singleShot

答案 4 :(得分:0)

这可能会帮助某人

msgBox.button(QMessageBox::Ok)->animateClick(5000);

5秒钟后,消息框关闭。