Search code examples
c++qtlayouttoolbarqtextedit

How to create a class that is a widget that has a QTextEdit and a QToolBar above the text edit


My intent is to create a QTextEdit with its reach text controls. The controls I want to put in a toolbar. But I have difficulties with controling the layout. The problem is that the overlap if I put a QTextEdit in a QWidget (my class inherits QWidget) which has a toolbar.

Another way I tried was the following: my class inherits QTextEdit, and it has a toolbar. Now the layout is different but not what I want. PLease help me to have a nice view.


Solution

  • Place your toolbar and QTextEdit in a layout inside your class which inherits QWidget. Layouts (see QVBoxLayout) positions items relative to each other making sure they don't overlap. If you don't use a layout, all child widgets will be created at position (0,0), meaning at the top-left corner of the parent widget.

    QWidget* widget = new QWidget();
    QToolBar* toolbar = new QToolBar(widget);
    QTextEdit* textedit = new QTextEdit(widget);
    
    QVBoxLayout* layout = new QVBoxLayout(widget);
    layout->addWidget(toolbar);
    layout->addWidget(textedit);
    

    And voila, the widgets don't overlap anymore.