项目中遇到了需要重写Qt源码中的对话框
static void displayRenameFailedMessage(const QString &newName) 这个实现在源码里,
想重写修改QMessageBox的展示。
上代码
void setupMessageBoxEventFilter(QApplication &app) {
WindowManager *windowManager = new WindowManager();
auto eventFilter = new MessageBoxEventFilter();
app.installEventFilter(eventFilter);
QObject::connect(eventFilter, &MessageBoxEventFilter::sigCloseWidget,
windowManager, &WindowManager::closeWidget,Qt::QueuedConnection);
}
class WindowManager : public QObject {
Q_OBJECT
public slots:
void closeWidget(QWidget *widget) {
if (widget) {
widget->close(); // 关闭接收到的窗口
}
}
};
class MessageBoxEventFilter : public QObject {
Q_OBJECT
signals:
void sigCloseWidget(QWidget *widget);
protected:
bool eventFilter(QObject *obj, QEvent *event) override {
if (AndyMessageBox *msgBox = qobject_cast<AndyMessageBox*>(obj)){
return QObject::eventFilter(obj, event);
}
if (QMessageBox *msgBox = qobject_cast<QMessageBox*>(obj)) {
qDebug()<<msgBox->objectName()<< " event type is "<< event->type();
//
switch (event->type()) {
case QEvent::Show:
{
msgBox->setWindowOpacity(0);
AndyMessageBox *customDialog = new AndyMessageBox(msgBox->parentWidget());
customDialog->setObjectName("shixingya" );
customDialog->setWindowTitle("andy -- "+ msgBox->windowTitle());
customDialog->setText(msgBox->text());
customDialog->resize(1800,500);
customDialog->exec();
emit sigCloseWidget(msgBox); // 发出关闭信号
}
break;
default:
break;
}
}
return QObject::eventFilter(obj, event);
}
};