我读了 QMessageBox 的源代码,看到这些行:
void QMessageBoxPrivate::setupLayout()
{
Q_Q(QMessageBox);
delete q->layout();
QGridLayout *grid = new QGridLayout;
bool hasIcon = !iconLabel->pixmap(Qt::ReturnByValue).isNull();
if (hasIcon)
grid->addWidget(iconLabel,2,1,Qt::AlignTop);
iconLabel->setVisible(hasIcon);
#ifdef Q_OS_MAC
QSpacerItem *indentSpacer = new QSpacerItem(14,QSizePolicy::Fixed,QSizePolicy::Fixed);
#else
QSpacerItem *indentSpacer = new QSpacerItem(hasIcon ? 7 : 15,QSizePolicy::Fixed);
#endif
grid->addItem(indentSpacer,hasIcon ? 1 : 0,1);
grid->addWidget(label,hasIcon ? 2 : 1,1);
...
所以去除左边空格的方法是去除网格布局中的 indentSpacer :
QMessageBox msgBox(QMessageBox::NoIcon,"My Title","This is my text that I want to display.\nBut there is annoying left margin that I can't remove whatever I try.\n",QMessageBox::StandardButton::Ok);
QLabel *msg_label;
msg_label = msgBox.findChild<QLabel*>("qt_msgbox_label");
msg_label->setStyleSheet("* { color: blue; margin-left: 0; margin-right: 3; }");
QGridLayout *lay = msgBox.findChild<QGridLayout *>();
lay->removeItem(lay->itemAt(0));
msgBox.exec();
成功图片:
本文链接:https://www.f2er.com/266482.html