Qt: custom widget in QScrollArea

I am trying to create my own widget. My widget manifests itself if it is not inside the scroll pane. Below is the code. If I changed if (0) to if (1) inside the MainWindow constructor, it will not display the string "Hello World". I suggest that I should (re) implement some additional methods, but so far I have not been able to find the correct ones with trial and error.

// hellowidget.h #ifndef HELLOWIDGET_H #define HELLOWIDGET_H #include <QtGui> class HelloWidget : public QWidget { Q_OBJECT public: HelloWidget(QWidget *parent = 0); void paintEvent(QPaintEvent *event); }; #endif // HELLOWIDGET_H // hellowidget.cpp #include "hellowidget.h" HelloWidget::HelloWidget(QWidget *parent) : QWidget(parent) { } void HelloWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawText(rect(), Qt::AlignCenter, "Hello World"); } // mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGui> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); private: }; #endif // MAINWINDOW_H // mainwindow.cpp #include "mainwindow.h" #include "hellowidget.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { HelloWidget *hello = new HelloWidget; QWidget *central = hello; if( 0 ) { QScrollArea *scroll = new QScrollArea ; scroll->setWidget(hello); central = scroll; } setCentralWidget( central ); } MainWindow::~MainWindow() { } // main.cpp #include <QtGui/QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } 
+4
source share
3 answers

You just need to give your HelloWidget size and place.

Add this line to your code.

 hello->setGeometry(QRect(110, 80, 120, 80)); 



Or, if you want to fill the scroll pane with widgets:

 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QScrollArea *const scroll(new QScrollArea); QHBoxLayout *const layout(new QHBoxLayout(scroll)); HelloWidget *const hello(new HelloWidget); hello->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); layout->addWidget(hello); setCentralWidget( scroll ); } 
+8
source

Per Qt docs : "When using the scroll pane to display the contents of a custom widget, it is important to ensure that the size of the hint of the child widget is set to the appropriate value. If the child widget uses the standard QWidget, you may need to call QWidget :: setMinimumSize () to make sure that the contents of the widget are correctly shown in the scroll pane. "

Does this work correctly if you follow these instructions?

+3
source

I also pulled my hair out, but ended up finding QScrollArea setWidgetResizable , which is why QScrollArea allowed my widget to expand upwards in the available space.

+3
source

Source: https://habr.com/ru/post/1286263/


All Articles