C++Qt在用两个QRadioButton控制创建的Qcustom的图形,选择第一个QRadioButton,出现Qcustom中第一个图形,选择第二个QRadioButton,出现Qcustom中的第二个图形使用头文件源文件的形式呈现
时间: 2024-03-10 10:47:35 浏览: 15
好的,您需要定义一个继承自 QWidget 的自定义控件,我们称之为 MyCustomWidget。
MyCustomWidget.h 文件的代码:
```cpp
#ifndef MYCUSTOMWIDGET_H
#define MYCUSTOMWIDGET_H
#include <QWidget>
#include "qcustomplot.h"
class MyCustomWidget : public QWidget
{
Q_OBJECT
public:
explicit MyCustomWidget(QWidget *parent = nullptr);
private:
QCustomPlot *m_customPlot1;
QCustomPlot *m_customPlot2;
};
#endif // MYCUSTOMWIDGET_H
```
MyCustomWidget.cpp 文件的代码:
```cpp
#include "MyCustomWidget.h"
#include <QRadioButton>
#include <QVBoxLayout>
MyCustomWidget::MyCustomWidget(QWidget *parent) : QWidget(parent)
{
// 创建两个 QCustomPlot 控件
m_customPlot1 = new QCustomPlot(this);
m_customPlot2 = new QCustomPlot(this);
// 创建两个 QRadioButton 控件
auto *radioButton1 = new QRadioButton("图形1", this);
auto *radioButton2 = new QRadioButton("图形2", this);
// 创建一个垂直布局管理器
auto *layout = new QVBoxLayout(this);
layout->addWidget(radioButton1);
layout->addWidget(radioButton2);
layout->addWidget(m_customPlot1);
layout->addWidget(m_customPlot2);
// 当 radioButton1 被选中时,显示 m_customPlot1,隐藏 m_customPlot2
connect(radioButton1, &QRadioButton::toggled, [this](bool checked){
m_customPlot1->setVisible(checked);
m_customPlot2->setVisible(!checked);
});
// 当 radioButton2 被选中时,显示 m_customPlot2,隐藏 m_customPlot1
connect(radioButton2, &QRadioButton::toggled, [this](bool checked){
m_customPlot2->setVisible(checked);
m_customPlot1->setVisible(!checked);
});
// 初始状态下显示 m_customPlot1,隐藏 m_customPlot2
m_customPlot1->setVisible(true);
m_customPlot2->setVisible(false);
// 设置 QCustomPlot 控件的大小策略
m_customPlot1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_customPlot2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// 设置 QCustomPlot 控件的样式
m_customPlot1->addGraph();
m_customPlot1->graph(0)->setData({1,2,3}, {2,4,1});
m_customPlot1->replot();
m_customPlot2->addGraph();
m_customPlot2->graph(0)->setData({1,2,3}, {3,1,4});
m_customPlot2->replot();
}
```
在主窗口中使用 MyCustomWidget 控件:
```cpp
#include "MainWindow.h"
#include "MyCustomWidget.h"
#include <QHBoxLayout>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
auto *widget = new MyCustomWidget(this);
setCentralWidget(widget);
}
```
这样,当用户选择第一个 QRadioButton 时,就会显示 MyCustomWidget 中的 m_customPlot1,而选择第二个 QRadioButton 时,则会显示 m_customPlot2。