Why does the border of QWidget cover the contents?

时光总嘲笑我的痴心妄想 提交于 2019-12-10 23:31:18

问题


I have a custom widget derived from QWidget, which has a minimumSize of (30, 30) and a QLabel as a childWidget:

MyWidget::MyWidget (QWidget *parent, QPoint p,
                  QWidget *childWidget) : QWidget (parent)
{
    childWidget = this->childWidget;
    setAttribute (Qt::WA_DeleteOnClose);
    this->move (p);
    verticalLayout = new QVBoxLayout (this);

    if (childWidget != NULL)
    {
        childWidget->setParent (this);
        childWidget->releaseMouse();
        childWidget->setAttribute (Qt::WA_TransparentForMouseEvents,     true);
        verticalLayout->addWidget (childWidget);
    }
    this->setLayout(verticalLayout);
};

MyWidget::mouseMoveEvent (QMouseEvent *e)
{
    if (! (e->button() == Qt::RightButton))
    {
        this->update();
        this->raise();
    }
}

void MyWidget::mouseReleaseEvent (QMouseEvent *evt)
{
    QWidget::mouseReleaseEvent(evt);
    this->update();
}

MyWidget::mousePressEvent (QMouseEvent *e)
{
    if (! (e->button() == Qt::RightButton))
    {

        this->update();
        this->raise();
    }
}

void MyWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::darkGreen);
    painter.drawRect(1, 2, 6, 4);
    painter.setPen(Qt::darkGray);
    painter.drawLine(2, 8, 6, 2);
}

//And some getter/setter methods.

In order to set a border to the widget I use the following code:

 customWidget->setStyleSheet("*{border-width:" +
    2 +
    ";border-style:solid;border-color:" +
    #FFFFFF + " ;color:white;}");

It looks like this (the parent widget has an orange background):

.

When I change the border-width to 10, the border covers the contents:

Both images show the widget in its minimum height.

To me it looks as if the border were applied inwards. What shall I modify to point the border outwards, so for a larger border-width the text remains visible?


回答1:


Cause

The border does go outwards:

You have a problem with the size. (30, 30) is too small for this border. 30 - 2*10 (the minimum height - 2 times the width of the border) equals 10. Your font is larger than 10px, so it does not fit in the remaining space.

Solution

You might want to set a reasonable size, e.g. (100, 50). However, setting the minimum size is not flexible, meaning, that it does not account for changes in the widget's content. If the sizeHint and minimumSizeHint are implemented though, the necessary space will be reported whenever needed, as it is done in QLabel for example.

Since you already have a QLabel as a child widget, just avoid setting the minimumSize of your custom widget and the correct size will be calculated automatically.



来源:https://stackoverflow.com/questions/52697845/why-does-the-border-of-qwidget-cover-the-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!