类和继承qt

Classes and inheritance qt

本文关键字:qt 继承      更新时间:2023-10-16

我有两个类:

.cpp

MainWindow::MainWindow(QWidget *parent):
QMainWindow(parent) {
}
...
Inheritor:Inheritor(QWidget *parent):
MainWindow(parent) {
...
}

.h

class MainWindow : public QMainWindow
{
  Q_OBJECT
  QWidget *centralWidget;
public:
  MainWindow (QWidget* parent=0);
  QwtPlot *funPlot;
}
  class Inheritor : public MainWindow
{
Q_OBJECT
  QWidget *centralWidget;
public:
  Inheritor (QWidget* parent=0);
...
}

这是正确的认识吗?我有一个分割错误。我想它就在这里。我使用在MainWindow类中声明的可变funPlot。也许我的遗产是错误的。你能帮我吗?

void Inheritor::setCheckBox() {
    first_b = new QCheckBox("option 1");
    second_b = new QCheckBox("option 2");
    third_b = new QCheckBox("option 3");
    fourth_b = new QCheckBox("option 4");
    QPushButton *drawButton = new QPushButton("Draw");
    QVBoxLayout *rightLayout = new QVBoxLayout;
    rightLayout->addWidget(first_b);
    rightLayout->addWidget(second_b);
    rightLayout->addWidget(third_b);
    rightLayout->addWidget(fourth_b);
    rightLayout->addWidget(drawButton);
    rightLayout->addStretch();
    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(funPlot);
    mainLayout->addLayout(rightLayout);
    QWidget *cent = new QWidget();
    cent->setLayout(mainLayout);
    setCentralWidget(cent);
    resize(640,480);
    connect(first_b, SIGNAL(clicked()), this, SLOT(addPoints()));
    connect(second_b, SIGNAL(clicked()), this, SLOT(addPoints()));
    connect(third_b, SIGNAL(clicked()), this, SLOT(addPoints()));
    connect(fourth_b, SIGNAL(clicked()), this, SLOT(addPoints()));
    drawButton->setCheckable(true);
    connect(drawButton, SIGNAL(clicked()), this, SLOT(drawCurve()));
}

funPlot指针未分配。

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent) 
{
    funPlot = new QwtPlot( this );
}

如果没有分配,程序很可能会在使用funPlot时发生seg故障(就像在Inheritor::setCheckBox中使用mainLayout->addWidget(funPlot);时一样)