如何在QT中将小部件的内容添加和显示到另一个小部件上

How to add and show the contents of a widget onto another widget in QT?

本文关键字:小部 添加 显示 另一个 QT      更新时间:2023-10-16

我创建了一个类 horrizontalprogressbar,在其中我创建了一个简单的进度条。我有另一个叫做主窗口的类,我想在主窗口上访问和显示 horrizontalprogressbar 的内容。我在这里尝试了很多东西,但我仍然在单独的窗口中不断获得可怕的进度条和主窗口。无论如何可以在同一窗口中显示它们。由于我是QT的新手,我将非常感谢我能得到的任何帮助来解决这个问题。

请在下面找到代码:-Horrizontalprogressbar.h

#ifndef HORRIZONTALPROGRESSBAR_H
#define HORRIZONTALPROGRESSBAR_H
#include <QProgressBar>
#include <QWidget>
class horrizontalprogressbar: public QProgressBar
{
    Q_OBJECT
public:
    horrizontalprogressbar();
    QProgressBar progressBar_horizontal;
};
#endif // HORRIZONTALPROGRESSBAR_H

恐怖进步吧.cpp

#include "horrizontalprogressbar.h"
horrizontalprogressbar::horrizontalprogressbar()
{
    progressBar_horizontal.setRange(0,5);
    progressBar_horizontal.setValue(2.5);
    progressBar_horizontal.setFixedSize(300,50);
    //progressBar_horizontal.show();
}

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtWidgets>
class horrizontalprogressbar;
class MainWindow : public QMainWindow
{
    Q_OBJECT
private:
    horrizontalprogressbar *progressbar_H;
public:
    MainWindow();//(QWidget *parent = 0);
    ~MainWindow();
};
#endif // MAINWINDOW_H

主窗口.cpp

#include "mainwindow.h"
#include "horrizontalprogressbar.h"
MainWindow::MainWindow()//(QWidget *parent)
   // : QMainWindow(parent)
{
    progressbar_H = new horrizontalprogressbar;
    setCentralWidget(progressbar_H);
    progressbar_H->setParent(this);
    //progressbar_H->setFixedSize(200,200);
    //progressbar_H->show();
}
MainWindow::~MainWindow()
{
}

主.cpp

#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.setFixedSize(800,600);
    w.setStyleSheet("QMainWindow {background: 'black';}");
    w.show();
    return a.exec();
}

它对我有用,请更改以下内容,以便在构造时应用新对象的设置:

#include "horrizontalprogressbar.h"
horrizontalprogressbar::horrizontalprogressbar()
{
   this->setRange(0,5);
   this->setValue(2.5);
   this->setFixedSize(300,50);
   //    progressBar_horizontal.show();
}