Repository navigation
Expand file tree
/
Copy pathmessagedialog.cpp
More file actions
610 lines (539 loc) · 19.9 KB
/
Copy pathmessagedialog.cpp
File metadata and controls
610 lines (539 loc) · 19.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
#include "messagedialog.h"
#include <QFont>
#include <QFontMetrics>
#include <QFrame>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QLabel>
#include <QList>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QPalette>
#include <QPushButton>
#include <QScreen>
#include <QShowEvent>
#include <QStyle>
#include <QTextBrowser>
#include <QTextDocument>
#include <QTextOption>
#include <QToolButton>
#include <QVBoxLayout>
#include <QtMath>
namespace {
// 弹窗宽度按内容在上下限之间自适应:短提示不再被固定宽度拉出大片空白,
// 长文本仍然在最大宽度内换行。
const int kCardMinWidth = 340;
const int kCardMaxWidth = 460;
const int kBodyMargin = 22;
const int kMaxBodyWidth = kCardMaxWidth - kBodyMargin * 2;
const int kMinBodyHeight = 18;
// 正文滚动条的宽度(QSS 里 8px)加上少量余量,长文本时预留。
const int kScrollBarSpace = 12;
const int kIconSize = 36;
const int kHeaderSpacing = 12;
const int kCloseButtonSize = 26;
const int kFooterSpacing = 10;
QPixmap makeMessageIcon(MessageDialog::Icon type, int size,
qreal devicePixelRatio) {
if (type == MessageDialog::Icon::None) {
return QPixmap();
}
const qreal dpr = devicePixelRatio > 0 ? devicePixelRatio : 1.0;
const int pixels = qRound(size * dpr);
QPixmap pixmap(pixels, pixels);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing);
painter.scale(dpr, dpr);
QColor background;
QColor foreground;
switch (type) {
case MessageDialog::Icon::Success:
background = QColor(0xdc, 0xfc, 0xe7);
foreground = QColor(0x16, 0xa3, 0x4a);
break;
case MessageDialog::Icon::Warning:
background = QColor(0xfe, 0xf3, 0xc7);
foreground = QColor(0xd9, 0x77, 0x06);
break;
case MessageDialog::Icon::Critical:
background = QColor(0xfe, 0xe2, 0xe2);
foreground = QColor(0xdc, 0x26, 0x26);
break;
case MessageDialog::Icon::Question:
case MessageDialog::Icon::Information:
default:
background = QColor(0xdb, 0xea, 0xfe);
foreground = QColor(0x25, 0x63, 0xeb);
break;
}
const QRectF circle(1.5, 1.5, size - 3.0, size - 3.0);
painter.setPen(Qt::NoPen);
painter.setBrush(background);
painter.drawEllipse(circle);
const QPointF center = circle.center();
painter.setPen(
QPen(foreground, 2.2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
painter.setBrush(Qt::NoBrush);
switch (type) {
case MessageDialog::Icon::Success: {
QPainterPath path;
path.moveTo(center.x() - 6.0, center.y());
path.lineTo(center.x() - 1.5, center.y() + 4.5);
path.lineTo(center.x() + 6.5, center.y() - 4.5);
painter.drawPath(path);
break;
}
case MessageDialog::Icon::Warning:
case MessageDialog::Icon::Critical: {
painter.drawLine(QPointF(center.x(), center.y() - 7.0),
QPointF(center.x(), center.y() + 2.0));
painter.setPen(Qt::NoPen);
painter.setBrush(foreground);
painter.drawEllipse(QPointF(center.x(), center.y() + 7.0), 1.5, 1.5);
break;
}
case MessageDialog::Icon::Question: {
QFont font = painter.font();
font.setBold(true);
font.setPixelSize(qRound(size * 0.52));
painter.setFont(font);
painter.setPen(foreground);
painter.drawText(circle, Qt::AlignCenter, QStringLiteral("?"));
break;
}
case MessageDialog::Icon::Information:
default: {
painter.setPen(Qt::NoPen);
painter.setBrush(foreground);
painter.drawEllipse(QPointF(center.x(), center.y() - 6.5), 1.5, 1.5);
painter.setPen(QPen(foreground, 2.2, Qt::SolidLine, Qt::RoundCap));
painter.drawLine(QPointF(center.x(), center.y() - 2.0),
QPointF(center.x(), center.y() + 7.0));
break;
}
}
painter.end();
pixmap.setDevicePixelRatio(dpr);
return pixmap;
}
} // namespace
MessageDialog::MessageDialog(QWidget *parent) : QDialog(parent) {
initUi();
setIcon(Icon::Information);
updateButtons();
updateBodyHeight();
}
MessageDialog::~MessageDialog() = default;
void MessageDialog::initUi() {
setObjectName(QStringLiteral("messageDialog"));
setWindowTitle(tr("提示"));
setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
// 只面向带合成器的现代桌面:透明窗口配合 QSS 圆角即可,不再使用
// 窗口蒙版兜底,也就不需要查询系统合成器。
setAttribute(Qt::WA_TranslucentBackground);
setModal(true);
setWindowModality(parentWidget() ? Qt::WindowModal : Qt::ApplicationModal);
setFixedWidth(kCardMinWidth);
// 弹窗本身就是卡片:不再保留透明/浅色外边距,避免在深色背景上出现白边。
QVBoxLayout *outerLayout = new QVBoxLayout(this);
outerLayout->setContentsMargins(0, 0, 0, 0);
outerLayout->setSpacing(0);
QFrame *card = new QFrame(this);
card->setObjectName(QStringLiteral("messageDialogCard"));
outerLayout->addWidget(card);
QVBoxLayout *cardLayout = new QVBoxLayout(card);
cardLayout->setContentsMargins(0, 0, 0, 0);
cardLayout->setSpacing(0);
header = new QWidget(card);
header->setObjectName(QStringLiteral("messageDialogHeader"));
header->installEventFilter(this);
QHBoxLayout *headerLayout = new QHBoxLayout(header);
headerLayout->setContentsMargins(kBodyMargin, 18, 14, 8);
headerLayout->setSpacing(kHeaderSpacing);
iconLabel = new QLabel(header);
iconLabel->setFixedSize(kIconSize, kIconSize);
iconLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
headerLayout->addWidget(iconLabel, 0, Qt::AlignVCenter);
titleLabel = new QLabel(header);
titleLabel->setObjectName(QStringLiteral("messageDialogTitle"));
titleLabel->setTextFormat(Qt::PlainText);
titleLabel->setWordWrap(true);
titleLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
QFont titleFont = font();
if (titleFont.pointSizeF() > 0) {
titleFont.setPointSizeF(titleFont.pointSizeF() + 1.5);
}
titleFont.setWeight(QFont::DemiBold);
titleLabel->setFont(titleFont);
headerLayout->addWidget(titleLabel, 1, Qt::AlignVCenter);
closeButton = new QToolButton(header);
closeButton->setObjectName(QStringLiteral("messageDialogCloseButton"));
closeButton->setIcon(QIcon(QStringLiteral(":/icons/close.png")));
closeButton->setIconSize(QSize(12, 12));
closeButton->setAutoRaise(true);
closeButton->setCursor(Qt::PointingHandCursor);
closeButton->setToolTip(tr("关闭"));
closeButton->setFixedSize(kCloseButtonSize, kCloseButtonSize);
connect(closeButton, &QToolButton::clicked, this, [this]() { reject(); });
headerLayout->addWidget(closeButton, 0, Qt::AlignVCenter);
cardLayout->addWidget(header);
QWidget *bodyContainer = new QWidget(card);
QVBoxLayout *bodyLayout = new QVBoxLayout(bodyContainer);
bodyLayout->setContentsMargins(kBodyMargin, 0, kBodyMargin, 18);
bodyLayout->setSpacing(0);
body = new QTextBrowser(bodyContainer);
body->setObjectName(QStringLiteral("messageDialogBody"));
body->setFrameShape(QFrame::NoFrame);
body->setReadOnly(true);
body->setOpenExternalLinks(false);
body->setTextInteractionFlags(Qt::TextSelectableByMouse);
body->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
body->setFocusPolicy(Qt::ClickFocus);
body->setFixedWidth(kMaxBodyWidth);
QTextOption textOption = body->document()->defaultTextOption();
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
body->document()->setDefaultTextOption(textOption);
body->document()->setDocumentMargin(0);
QFont bodyFont = font();
body->setFont(bodyFont);
QPalette bodyPalette = body->palette();
bodyPalette.setColor(QPalette::Text, QColor(0x47, 0x55, 0x69));
bodyPalette.setColor(QPalette::Base, QColor(0xff, 0xff, 0xff));
body->setPalette(bodyPalette);
body->viewport()->setPalette(bodyPalette);
bodyLayout->addWidget(body);
cardLayout->addWidget(bodyContainer);
QFrame *separator = new QFrame(card);
separator->setObjectName(QStringLiteral("messageDialogSeparator"));
separator->setFrameShape(QFrame::NoFrame);
separator->setFixedHeight(1);
cardLayout->addWidget(separator);
QWidget *footer = new QWidget(card);
QHBoxLayout *footerLayout = new QHBoxLayout(footer);
footerLayout->setContentsMargins(kBodyMargin, 6, kBodyMargin, 6);
footerLayout->setSpacing(kFooterSpacing);
footerLayout->addStretch(1);
cancelButton = new QPushButton(tr("取消"), footer);
cancelButton->setObjectName(QStringLiteral("messageDialogSecondaryButton"));
cancelButton->setMinimumWidth(88);
cancelButton->setFixedHeight(32);
cancelButton->setAutoDefault(false);
connect(cancelButton, &QPushButton::clicked, this,
&MessageDialog::onCancelClicked);
footerLayout->addWidget(cancelButton);
confirmButton = new QPushButton(tr("确定"), footer);
confirmButton->setObjectName(QStringLiteral("messageDialogPrimaryButton"));
confirmButton->setMinimumWidth(88);
confirmButton->setFixedHeight(32);
connect(confirmButton, &QPushButton::clicked, this,
&MessageDialog::onConfirmClicked);
footerLayout->addWidget(confirmButton);
cardLayout->addWidget(footer);
}
void MessageDialog::setIcon(Icon icon) {
const QPixmap pixmap = makeMessageIcon(icon, kIconSize, devicePixelRatioF());
if (pixmap.isNull()) {
iconLabel->clear();
iconLabel->hide();
} else {
iconLabel->setPixmap(pixmap);
iconLabel->show();
}
updateBodyHeight();
}
void MessageDialog::setTitleText(const QString &title) {
titleLabel->setText(title);
setWindowTitle(title.isEmpty() ? tr("提示") : title);
updateBodyHeight();
}
void MessageDialog::setText(const QString &text) {
body->setPlainText(text);
updateBodyHeight();
}
void MessageDialog::setStandardButtons(int buttons) {
this->buttons = buttons == 0 ? Ok : buttons;
updateButtons();
}
void MessageDialog::setDefaultButton(StandardButton button) {
defaultButton = button;
updateButtons();
}
void MessageDialog::setConfirmButtonText(const QString &text) {
customConfirmText = true;
confirmButton->setText(text);
updateBodyHeight();
}
void MessageDialog::setCancelButtonText(const QString &text) {
customCancelText = true;
cancelButton->setText(text);
updateBodyHeight();
}
void MessageDialog::setConfirmDestructive(bool destructive) {
this->destructive = destructive;
applyConfirmStyle();
}
void MessageDialog::updateButtons() {
if ((buttons & (Ok | Yes | Cancel | No)) == 0) {
buttons = Ok;
}
const bool showConfirm = (buttons & (Ok | Yes)) != 0;
const bool showCancel = (buttons & (Cancel | No)) != 0;
confirmButton->setVisible(showConfirm);
cancelButton->setVisible(showCancel);
if (!customConfirmText) {
confirmButton->setText((buttons & Yes) ? tr("是") : tr("确定"));
}
if (!customCancelText) {
cancelButton->setText((buttons & No) ? tr("否") : tr("取消"));
}
const bool cancelDefault =
(defaultButton == Cancel || defaultButton == No) && showCancel;
confirmButton->setDefault(!cancelDefault && showConfirm);
confirmButton->setAutoDefault(!cancelDefault && showConfirm);
cancelButton->setDefault(cancelDefault);
cancelButton->setAutoDefault(cancelDefault);
applyConfirmStyle();
updateBodyHeight();
}
int MessageDialog::maxBodyHeight() const {
QScreen *currentScreen = nullptr;
if (QWidget *anchor = parentWidget()) {
currentScreen =
QGuiApplication::screenAt(anchor->mapToGlobal(anchor->rect().center()));
}
if (!currentScreen) {
currentScreen = QGuiApplication::primaryScreen();
}
const int screenHeight =
currentScreen ? currentScreen->availableGeometry().height() : 900;
// 为标题栏、按钮区和屏幕边距预留约 250px,剩余空间都给正文。
return qBound(120, screenHeight - 250, 520);
}
int MessageDialog::updateContentWidth() {
// 让文档按不换行状态排版,用 idealWidth 取最长一行的实际宽度;
// 字体度量和文本布局的取整方式不同,直接用文档测量可避免一行被挤成两行。
QTextDocument *document = body->document();
document->setTextWidth(-1);
int textWidth = 0;
if (!body->toPlainText().isEmpty()) {
textWidth = qCeil(document->idealWidth()) + 2;
}
// 标题行:左右边距 + 图标 + 间距 + 标题 + 间距 + 关闭按钮。
int headerWidth = kBodyMargin + 14 + kHeaderSpacing + kCloseButtonSize;
if (!iconLabel->isHidden()) {
headerWidth += kIconSize + kHeaderSpacing;
}
headerWidth +=
QFontMetrics(titleLabel->font()).boundingRect(titleLabel->text()).width();
// 底部:只统计当前可见的按钮。
int footerWidth = kBodyMargin * 2;
bool hasButton = false;
const QList<QPushButton *> footerButtons = {cancelButton, confirmButton};
for (QPushButton *button : footerButtons) {
if (button->isHidden()) {
continue;
}
if (hasButton) {
footerWidth += kFooterSpacing;
}
footerWidth += qMax(button->minimumWidth(), button->sizeHint().width());
hasButton = true;
}
const int neededWidth =
qMax(textWidth + kBodyMargin * 2, qMax(headerWidth, footerWidth));
const int cardWidth = qBound(kCardMinWidth, neededWidth, kCardMaxWidth);
const int bodyWidth = cardWidth - kBodyMargin * 2;
setFixedWidth(cardWidth);
body->setFixedWidth(bodyWidth);
return bodyWidth;
}
void MessageDialog::updateBodyHeight() {
const int bodyWidth = updateContentWidth();
body->document()->setDocumentMargin(0);
// 正文宽度固定,先按完整宽度测量;超过屏幕可用高度时再给滚动条让出宽度。
body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
body->document()->setTextWidth(bodyWidth);
int height = qCeil(body->document()->size().height()) + 2;
const int limit = maxBodyHeight();
if (height > limit) {
body->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
body->document()->setTextWidth(bodyWidth - kScrollBarSpace);
const int wrappedHeight = qCeil(body->document()->size().height()) + 2;
if (wrappedHeight <= limit) {
// 让出滚动条宽度后反而能完整显示,就不需要滚动条。
body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
height = wrappedHeight;
} else {
height = limit;
}
}
body->setFixedHeight(qMax(kMinBodyHeight, height));
adjustSize();
}
void MessageDialog::applyConfirmStyle() {
confirmButton->setProperty("primary", !destructive);
confirmButton->setProperty("danger", destructive);
confirmButton->style()->unpolish(confirmButton);
confirmButton->style()->polish(confirmButton);
confirmButton->update();
}
void MessageDialog::onConfirmClicked() {
clickedButton_ = (buttons & Yes) ? Yes : Ok;
accept();
}
void MessageDialog::onCancelClicked() {
clickedButton_ = (buttons & No) ? No : Cancel;
reject();
}
void MessageDialog::accept() {
if (clickedButton_ == NoButton) {
clickedButton_ = (buttons & Yes) ? Yes : Ok;
}
QDialog::accept();
}
void MessageDialog::reject() {
if (clickedButton_ == NoButton) {
if (buttons & (Cancel | No)) {
clickedButton_ = (buttons & No) ? No : Cancel;
} else if (buttons & Yes) {
clickedButton_ = No;
} else {
clickedButton_ = Ok;
}
}
QDialog::reject();
}
void MessageDialog::showEvent(QShowEvent *event) {
QDialog::showEvent(event);
if (!positioned) {
positioned = true;
adjustSize();
QRect anchorRect;
if (QWidget *anchor = parentWidget()) {
QWidget *window = anchor->window();
if (window && window != this) {
anchor = window;
}
anchorRect = QRect(anchor->mapToGlobal(QPoint(0, 0)), anchor->size());
} else if (QScreen *screen = QGuiApplication::primaryScreen()) {
anchorRect = screen->availableGeometry();
}
QRect target(QPoint(0, 0), size());
target.moveCenter(anchorRect.center());
if (QScreen *screen = QGuiApplication::screenAt(anchorRect.center())) {
const QRect available = screen->availableGeometry();
if (target.left() < available.left()) {
target.moveLeft(available.left());
}
if (target.top() < available.top()) {
target.moveTop(available.top());
}
if (target.right() > available.right()) {
target.moveRight(available.right());
}
if (target.bottom() > available.bottom()) {
target.moveBottom(available.bottom());
}
}
move(target.topLeft());
}
raise();
activateWindow();
// 尊重默认按钮:删除/覆盖等危险操作默认聚焦“取消”,避免误按空格。
const bool cancelDefault = defaultButton == Cancel || defaultButton == No;
if (cancelDefault && cancelButton->isVisible()) {
cancelButton->setFocus();
} else if (confirmButton->isVisible()) {
confirmButton->setFocus();
} else if (cancelButton->isVisible()) {
cancelButton->setFocus();
}
}
bool MessageDialog::eventFilter(QObject *watched, QEvent *event) {
if (watched == header) {
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::LeftButton) {
dragging = true;
dragOffset = mouseEvent->globalPos() - frameGeometry().topLeft();
return true;
}
} else if (event->type() == QEvent::MouseMove && dragging) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->buttons() & Qt::LeftButton) {
move(mouseEvent->globalPos() - dragOffset);
return true;
}
} else if (event->type() == QEvent::MouseButtonRelease) {
dragging = false;
return true;
}
}
return QDialog::eventFilter(watched, event);
}
MessageDialog::StandardButton
MessageDialog::showMessage(QWidget *parent, Icon icon, const QString &title,
const QString &text, int buttons,
StandardButton defaultButton) {
MessageDialog dialog(parent);
dialog.setIcon(icon);
dialog.setTitleText(title);
dialog.setText(text);
dialog.setStandardButtons(buttons);
dialog.setDefaultButton(defaultButton);
dialog.exec();
return dialog.clickedButton();
}
MessageDialog::StandardButton
MessageDialog::information(QWidget *parent, const QString &title,
const QString &text, int buttons,
StandardButton defaultButton) {
return showMessage(parent, Icon::Information, title, text, buttons,
defaultButton);
}
MessageDialog::StandardButton
MessageDialog::success(QWidget *parent, const QString &title,
const QString &text, int buttons,
StandardButton defaultButton) {
return showMessage(parent, Icon::Success, title, text, buttons,
defaultButton);
}
MessageDialog::StandardButton
MessageDialog::warning(QWidget *parent, const QString &title,
const QString &text, int buttons,
StandardButton defaultButton) {
return showMessage(parent, Icon::Warning, title, text, buttons,
defaultButton);
}
MessageDialog::StandardButton
MessageDialog::critical(QWidget *parent, const QString &title,
const QString &text, int buttons,
StandardButton defaultButton) {
return showMessage(parent, Icon::Critical, title, text, buttons,
defaultButton);
}
MessageDialog::StandardButton
MessageDialog::question(QWidget *parent, const QString &title,
const QString &text, int buttons,
StandardButton defaultButton) {
return showMessage(parent, Icon::Question, title, text, buttons,
defaultButton);
}
bool MessageDialog::confirm(QWidget *parent, const QString &title,
const QString &text, const QString &confirmText,
const QString &cancelText, bool destructive) {
MessageDialog dialog(parent);
dialog.setIcon(destructive ? Icon::Warning : Icon::Question);
dialog.setTitleText(title);
dialog.setText(text);
dialog.setStandardButtons(Yes | No);
dialog.setDefaultButton(No);
dialog.setConfirmButtonText(confirmText);
dialog.setCancelButtonText(cancelText);
dialog.setConfirmDestructive(destructive);
dialog.exec();
return dialog.clickedButton() == Yes;
}