Qt - set QWidget with a QWidget class
15:44 29 Oct 2016

I'm learning to use Qt and I want to extend the Terminal Example of Qt. I want to use its console.cpp in a QWidget from the Containers tab in the Design editor.

In the Terminal Example of Qt, this class is used like this:

ui->setupUi(this);
console = new Console;
console->setEnabled(false);
setCentralWidget(console);

But as I want to use it in a smaller QWidget, I don't know how to set it. Which method can I use as equivalent of setCentralWidget for my QWidget?

Image of the Design tab with the widget I want to set to the QWidget class

Can I also use the same QWidget in several tabs?

The console.cpp code is the following one.

#include "console.h"

#include 

#include 

Console::Console(QWidget *parent)
    : QPlainTextEdit(parent)
    , localEchoEnabled(false)
{
    document()->setMaximumBlockCount(100);
    QPalette p = palette();
    p.setColor(QPalette::Base, Qt::black);
    p.setColor(QPalette::Text, Qt::green);
    setPalette(p);

}

void Console::putData(const QByteArray &data)
{
    insertPlainText(QString(data));

    QScrollBar *bar = verticalScrollBar();
    bar->setValue(bar->maximum());
}

void Console::setLocalEchoEnabled(bool set)
{
    localEchoEnabled = set;
}

void Console::keyPressEvent(QKeyEvent *e)
{
    switch (e->key()) {
    case Qt::Key_Backspace:
    case Qt::Key_Left:
    case Qt::Key_Right:
    case Qt::Key_Up:
    case Qt::Key_Down:
        break;
    default:
        if (localEchoEnabled)
            QPlainTextEdit::keyPressEvent(e);
        emit getData(e->text().toLocal8Bit());
    }
}

void Console::mousePressEvent(QMouseEvent *e)
{
    Q_UNUSED(e)
    setFocus();
}

void Console::mouseDoubleClickEvent(QMouseEvent *e)
{
    Q_UNUSED(e)
}

void Console::contextMenuEvent(QContextMenuEvent *e)
{
    Q_UNUSED(e)
}

The Qt Example is this one: http://doc.qt.io/qt-5/qtserialport-terminal-example.html

Thanks so much!

c++ qt