在主小部件(控制台)QT下面添加小部件

Adding Widgets Underneath The Main Widget (Console) QT

本文关键字:小部 添加 QT 控制台      更新时间:2023-10-16

5使用Macos,现在我有一个中央小部件作为控制台屏幕。这显示了来自我的串行端口功能的输出。

在下面,我想添加一些其他小部件来做其他事情,比如按钮、滑块或液晶显示器。我在想怎么能做到这一点。

我目前拥有的代码:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //******* Set up
    ui->setupUi(this);
    console = new Console;
    console->setEnabled(false);
    setCentralWidget(console);
    //create serialport object
    serial = new QSerialPort(this);
    //create settings object
    settings = new SettingsDialog;
    ui->actionConnect->setEnabled(true);
    ui->actionDisconnect->setEnabled(false);
    ui->actionQuit->setEnabled(true);
    ui->actionConfigure->setEnabled(true);
    initActionsConnections();
    /************** Connection Events ***********************/
    connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,
            SLOT(handleError(QSerialPort::SerialPortError)));
    connect(serial, SIGNAL(readyRead()), this, SLOT(readData()));
    connect(console, SIGNAL(getData(QByteArray)), this, SLOT(writeData(QByteArray)));
}

然而,我希望这些小部件与控制台屏幕分离,控制台屏幕本身显示一些输出。所以我想添加以下小部件:

/************** Adding Widgets *********************/
//creation and attribution of slider
slider = new QSlider();
slider->resize(255, 20);
slider->setOrientation(Qt::Horizontal);
slider->setRange(0, 255); //0-255 is range we can read
//creation and attribution of the lcd
lcd = new QLCDNumber();
lcd->setSegmentStyle(QLCDNumber::Flat);
lcd->resize(255, 50);
//layout with slider and lcd
main_layout = new QVBoxLayout();
main_layout->addWidget(slider);
main_layout->addWidget(lcd);
//***********some way add this main_layout underneath the console **********/

我建议您将centralWidget布局设置为QVBoxLayout,并将您的项目添加到centralWidget->layout()

"主窗口"中的代码应该更改如下。

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->centralWidget->setLayout(new QVBoxLayout);
    console = new Console;
    console->setEnabled(false);
    // Add this line instead of setting your console as central widget.
    ui->centralWidget->layout()->addWidget(Console);
    .... //Continue with rest of the things
}

添加额外小部件的代码应该是这样的。

/************** Adding Widgets *********************/
//creation and attribution of slider
slider = new QSlider(this);
slider->resize(255, 20);
slider->setOrientation(Qt::Horizontal);
slider->setRange(0, 255); //0-255 is range we can read
//creation and attribution of the lcd
lcd = new QLCDNumber(this);
lcd->setSegmentStyle(QLCDNumber::Flat);
lcd->resize(255, 50);
//Adding the widgets created to the main layout.
ui->centralWidget->layout()->addWidget(slider);
ui->centralWidget->layout()->addWidget(lcd);

希望这就是你想要的。