首页 > 技术知识 > 正文

Qt自定义MessageBox

Qt自带的MessageBox很多时候都不满足需求,这时候就需要自定义MessageBox,这里只是简单的介绍自定义MessageBox的实现框架,具体想要实现什么样的内容还是需要自己实现,内容实现很简单,就和普通的界面一样。 代码实现:

#ifndef GDMCONFIGWIDGET_H #define GDMCONFIGWIDGET_H #include <QDialog> #include <QEventLoop> #include <QDebug> #include <QLabel> #include <QToolButton> class myMessageBox : public QDialog { Q_OBJECT public: myMessageBox(QWidget *parent = nullptr); ~myMessageBox(); public: bool static showMessageBox(QWidget* parent,QString title,QString text); void setText(QString str); public slots: void okClicked(); void cancelClicked(); private: void closeEvent(QCloseEvent *event); bool execs(); private: QEventLoop* m_eventLoop; bool ok = false; QLabel *text; QToolButton *okButton = nullptr; QToolButton *cancelButton = nullptr; }; #endif // GDMCONFIGWIDGET_H #include “mymessagebox.h” #include <QHBoxLayout> #include <QVBoxLayout> #include <QCloseEvent> myMessageBox::myMessageBox(QWidget *parent) : QDialog(parent) { //初始化界面显示 text = new QLabel(); okButton = new QToolButton(); cancelButton = new QToolButton(); okButton->setText(“OK”); cancelButton->setText(“cancel”); text->setAlignment(Qt::AlignCenter); QHBoxLayout *hLayout = new QHBoxLayout(); hLayout->addWidget(cancelButton,1); hLayout->addStretch(3); hLayout->addWidget(okButton,1); QVBoxLayout *vLayout = new QVBoxLayout(); vLayout->addWidget(text,5); vLayout->addLayout(hLayout,1); connect(okButton,SIGNAL(clicked()),this,SLOT(okClicked())); connect(cancelButton,SIGNAL(clicked()),this,SLOT(cancelClicked())); this->setLayout(vLayout); } myMessageBox::~myMessageBox() { } bool myMessageBox::showMessageBox(QWidget *parent, QString title, QString text) { myMessageBox * message = new myMessageBox(parent); message->setWindowTitle(title); message->setText(text); message->resize(600,200); //参数parent必须设置父窗口指针,否则模态设置无效; return message->execs(); } void myMessageBox::setText(QString str) { text->setText(str); } //确定点击 void myMessageBox::okClicked() { ok = true; close(); } //取消点击 void myMessageBox::cancelClicked() { ok = false; close(); } //关闭事件 void myMessageBox::closeEvent(QCloseEvent *event) { if (m_eventLoop != nullptr) { m_eventLoop->exit(); } event->accept(); } bool myMessageBox::execs() { // 因为QWidget没有exec()方法,所以需要自己定义来完成exec()方法; // 而exec()方法就是直接设置窗口显示为模态,并且窗口关闭结束后返回用户选择结果(按了确定还是取消按钮); // 这里也可以继承QDialog类,QDialog有自己的exec()方法,根据返回 Accepted, Rejected来决定是否按了确定按钮; this->setWindowModality(Qt::ApplicationModal); show(); // 使用事件循环QEventLoop ,不让exec()方法结束,在用户选择确定或者取消后,关闭窗口结束事件循环,并返回最后用户选择的结果; // 根据返回结果得到用户按下了确定还是取消,采取相应的操作。从而模拟出QDialog类的exec()方法; m_eventLoop = new QEventLoop(this); m_eventLoop->exec(); return ok; } int main(int argc, char *argv[]) { bool ok = myMessageBox::showMessageBox(this, QStringLiteral(“提示”), QStringLiteral(“是否删除”)); if(ok) { qDebug() << QString::fromLocal8Bit(“确定”); }else { qDebug() << QString::fromLocal8Bit(“取消”); } }
<

猜你喜欢