Search code examples
c++qtqwebengineview

How do I display a border around a QWebEngineView?


I have a QGraphicsWidget which I am using to paint and display a number of items including a QWebEngineView using the QGraphicsProxyWidget. I am able to load web content into QWebEngineView, but I would like to make the view contain a border. I have used "setStyleSheet" to try to add a border, but this does not appear to work. The following code is in the constructor of my QGraphicsWidget class to add the QWebEngineView:

 QWebEngineView * view = new QWebEngineView();
 view->setFixedWidth(700);
 view->setFixedHeight(200);
 view->setStyleSheet("border: 10px border-color: black");
 view->load(QUrl("qrc:/myresources/guidetext.html"));

 QGraphicsProxyWidget * proxyView = new QGraphicsProxyWidget(this);    
 proxyView->setWidget(view);

This is how it currently looks: enter image description here How I would like it to look like: enter image description here


Solution

  • Problem

    Normally, setting the Qt::WA_StyledBackground attribute, then the correct stylesheet and the content margins like that:

    view->setAttribute(Qt::WA_StyledBackground);
    view->setStyleSheet("border: 1px solid black;");
    view->setContentsMargins(1, 1, 1, 1);
    

    should do the trick.

    However, it seems that QWebEngineView does not respect the content margins:

    QWebEngineView covers the right and bottom border

    Workaround

    I would suggest you to make QWebEngineView child of another QWidget and style the parent widget instead.

    Example

    Here is an example I have prepared for you of how to change your code in order to implement the proposed solution:

    auto *proxyView = new QGraphicsProxyWidget();
    auto *widget = new QWidget();
    auto *view = new QWebEngineView(widget);
    auto *l = new QVBoxLayout(widget);
    
    l->addWidget(view);
    l->setContentsMargins(1, 1, 1, 1);
    
    widget->setAttribute(Qt::WA_StyledBackground);
    widget->setStyleSheet("border: 1px solid black;");
    widget->setFixedWidth(700);
    widget->setFixedHeight(200);
    
    view->load(QUrl("qrc:/myresources/guidetext.html"));
    
    proxyView->setWidget(widget);
    

    Result

    Here is the result when loading Google:

    The whole border around QWebEngineView is visible