C++Qt实现用两个QRadiobutton控制同一个Qcustomplot,只是显示在Qcustomplot的内容不同
时间: 2023-08-24 10:03:59 浏览: 111
可以通过以下步骤实现用两个QRadiobutton控制同一个Qcustomplot,只是显示在Qcustomplot的内容不同:
1. 在Qt Designer中将两个QRadiobutton添加到界面上,并命名为radioButton_1和radioButton_2。
2. 将一个Qcustomplot添加到界面上,并命名为customPlot。
3. 在界面类的头文件中添加以下代码:
```cpp
#include "qcustomplot.h"
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
QCustomPlot *m_customPlot;
QRadioButton *m_radioButton1;
QRadioButton *m_radioButton2;
private slots:
void on_radioButton1_clicked();
void on_radioButton2_clicked();
};
```
4. 在界面类的实现文件中添加以下代码:
```cpp
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// 获取QRadiobutton和Qcustomplot的指针
m_radioButton1 = ui->radioButton_1;
m_radioButton2 = ui->radioButton_2;
m_customPlot = ui->customPlot;
// 添加图表数据
QVector<double> x(101), y1(101), y2(101);
for (int i = 0; i < 101; ++i)
{
x[i] = i / 50.0 - 1;
y1[i] = qExp(-x[i]*x[i]) * qSin(x[i]*10);
y2[i] = qExp(-x[i]*x[i]) * qCos(x[i]*10);
}
// 添加两条曲线到Qcustomplot
QCPGraph *graph1 = m_customPlot->addGraph();
graph1->setData(x, y1);
QCPGraph *graph2 = m_customPlot->addGraph();
graph2->setData(x, y2);
// 设置曲线颜色
graph1->setPen(QPen(Qt::red));
graph2->setPen(QPen(Qt::blue));
// 设置Qcustomplot的坐标轴
m_customPlot->xAxis->setLabel("x");
m_customPlot->yAxis->setLabel("y");
m_customPlot->xAxis->setRange(-1, 1);
m_customPlot->yAxis->setRange(-1, 1);
// 连接RadioButton的clicked信号到槽函数
connect(m_radioButton1, &QRadioButton::clicked, this, &Widget::on_radioButton1_clicked);
connect(m_radioButton2, &QRadioButton::clicked, this, &Widget::on_radioButton2_clicked);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_radioButton1_clicked()
{
// 显示第一条曲线
m_customPlot->graph(0)->setVisible(true);
m_customPlot->graph(1)->setVisible(false);
m_customPlot->replot();
}
void Widget::on_radioButton2_clicked()
{
// 显示第二条曲线
m_customPlot->graph(0)->setVisible(false);
m_customPlot->graph(1)->setVisible(true);
m_customPlot->replot();
}
```
5. 运行程序,单击radioButton_1和radioButton_2,可以观察到Qcustomplot中显示的曲线发生变化。
阅读全文