问题描述
我想显示一些信息消息,为此我决定使用没有图标的 QMessageBox
,问题是小部件的左侧部分和文本之间存在巨大差距,试图通过设置边距和间距来删除它到 0,但除了左边的部分外,所有东西都被删除了。
这是我所拥有的一个简单示例。
QMessageBox messageBox(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);
messageBox.exec();
任何想法如何做到这一点,或者我应该创建自己的简单小部件?
解决方法
我读了 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();