简体   繁体   English

Qt-使用QWidget类设置QWidget

[英]Qt - set QWidget with a QWidget class

I'm learning to use Qt and I want to extend the Terminal Example of Qt. 我正在学习使用Qt,并且想扩展Qt的终端示例。 I want to use its console.cpp in a QWidget from de Containers tab in the Design editor. 我想在设计编辑器的de Containers选项卡中的QWidget中使用其console.cpp。

In the Terminal Example of Qt, this class is used like this: 在Qt的终端示例中,此类的用法如下:

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? 但是,由于我想在较小的QWidget中使用它,所以我不知道如何设置它,我的QWidget可以使用哪种方法等效于setCentralWidget? Image of the Design tab with the widget I want to set to the QWidget class 我要设置为QWidget类的窗口小部件的“设计”选项卡的图像

Can I also use the same QWidget in several tabs? 我还可以在多个标签中使用相同的QWidget吗?

The console.cpp code is the following one. console.cpp代码如下。

#include "console.h"

#include <QScrollBar>

#include <QtCore/QDebug>

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 Qt示例就是这样的: http : //doc.qt.io/qt-5/qtserialport-terminal-example.html

Thanks so much! 非常感谢!

If you're wanting to add it via designer just promote the QWidget that you added in your screegrab. 如果您想通过设计器添加它,只需推广您在screegrab中添加的QWidget。 (Right click > "Promote to..." > Fill in name & path to the console header). (右键单击>“升级为...”>填写控制台标题的名称和路径)。

Or not using promotion, you can add the console to a layout in code : 或不使用升级,您可以使用以下代码将控制台添加到布局:

Console* console = new Console();
ui->your_layout_name_here->addWidget( console );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM