Search code examples
c++qtlayoutqwebengineview

Resizing web page inside a spliter in qt


My question is simple, but I have been struggling to find the solution. I have the QMainWindow showed in the image, constructed in the QtCreator.

enter image description here

I want to load an html web page in the QWidget csWindow, for that I have placed a Qlabel label_pic where I load my web Page. This is code so far:

MainWindow::MainWindow(QWidget *parent, Project *project) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->project = project;

    QWebEngineView *view = new QWebEngineView(ui->label_pic);
    view->load(QUrl("http://localhost/myWeb.html"));

    ////works fine, for an image
    //QPixmap pix(":/img/imgs/someImage.png");
    //ui->label_pic->setPixmap(pix);

    //I also can load the web page in the QWidget csWindow but with the same result
    //QWebEngineView *view  = new QWebEngineView(ui->csWindow);
    //view->load(QUrl("http://localhost/myWebb.html"));

}

The page loads fine but it does not fit into the corresponding space, It is created with a fixed size and never resize. I want the web page to be resized when I move the spliters, but I have not succed doing it.

I have tried several approaches, first just put an image in label_pic, enable the property scaled contents and works fine. Now, I want to do the same with the web page.

Thanks in advance.


Solution

  • The page loads fine but it does not fit into the corresponding space

    This is because the size of the QWebEngineView is not know until it completes loading, so what you need is to connect to its signal loadFinished and resize label_pic :

    connect(view, &QWebEngineView::loadFinished, [this]() {this->ui->label_pic->resize(this->ui->csWindow->size());});
    

    I want the web page to be resized when I move the splitters

    Then also you need to connect to signal QSplitter::splitterMoved from all your splitters and resize both csWindow and label_pic like this:

    connect(ui->splitter, &QSplitter::splitterMoved, [this]() { this->view->resize(this->ui->csWindow->size()); this->ui->label_pic->resize(this->ui->csWindow->size());});
    connect(ui->splitter_2, &QSplitter::splitterMoved, [this]() { this->view->resize(this->ui->csWindow->size()); this->ui->label_pic->resize(this->ui->csWindow->size());});
    connect(ui->splitter_3, &QSplitter::splitterMoved, [this]() { this->view->resize(this->ui->csWindow->size()); this->ui->label_pic->resize(this->ui->csWindow->size());});
    

    and note that this would work best if you set a layout for your window, either from designer or adding code, for instance:

    QGridLayout *layout = new QGridLayout;
    layout->addWidget(ui->splitter_3);
    this->ui->centralWidget->setLayout(layout);
    

    and remember you should make all connect statements before you load the view.