crossplatform.ru

Здравствуйте, гость ( Вход | Регистрация )


  Ответ в кто-то работал с qcustomplot ?
Введите ваше имя
Подтвердите код

Введите в поле код из 6 символов, отображенных в виде изображения. Если вы не можете прочитать код с изображения, нажмите на изображение для генерации нового кода.
 

Опции сообщения
 Включить смайлы?
Иконки сообщения
(Опционально)
                                
                                
  [ Без иконки ]
 


Последние 10 сообщений [ в обратном порядке ]
skyer_ Дата 1.11.2014, 23:59
 
Цитата(Steklova Olga @ 30.10.2014, 20:13) *
Цитата(skyer_ @ 14.10.2014, 21:27) *
Приветствую, нужен совет как нарисовать горизонтальные гистограммы на qcustomplot.

  QCPCurve *gr1 = new QCPCurve(customPlot->xAxis, customPlot->yAxis);
  QCPCurve *gr2 = new QCPCurve(customPlot->xAxis, customPlot->yAxis);
  customPlot->addPlottable(gr1);
  customPlot->addPlottable(gr2);
  gr1->setPen(QPen(Qt::darkGreen, 50, Qt::SolidLine));
  gr2->setPen(QPen(Qt::darkGreen, 50, Qt::SolidLine));
  int pointCount = 2;
  QVector<double> x(pointCount), y(pointCount);
  x[0] = 0.0; x[1] = 120.0;  y[0] = 20.0; y[1] = y[0];
  gr1->setData(x, y);
  x[0] = 0.0; x[1] = 150.0;  y[0] = 50.0; y[1] = y[0];
  gr2->setData(x, y);
  customPlot->axisRect()->setupFullAxesBox();
  customPlot->xAxis->setRange(0.0, 200.0);
  customPlot->yAxis->setRange(0.0, 100.0);



Благодарю, сейчас буду пробовать.
Steklova Olga Дата 30.10.2014, 20:13
 
Цитата(skyer_ @ 14.10.2014, 21:27) *
Приветствую, нужен совет как нарисовать горизонтальные гистограммы на qcustomplot.

  QCPCurve *gr1 = new QCPCurve(customPlot->xAxis, customPlot->yAxis);
  QCPCurve *gr2 = new QCPCurve(customPlot->xAxis, customPlot->yAxis);
  customPlot->addPlottable(gr1);
  customPlot->addPlottable(gr2);
  gr1->setPen(QPen(Qt::darkGreen, 50, Qt::SolidLine));
  gr2->setPen(QPen(Qt::darkGreen, 50, Qt::SolidLine));
  int pointCount = 2;
  QVector<double> x(pointCount), y(pointCount);
  x[0] = 0.0; x[1] = 120.0;  y[0] = 20.0; y[1] = y[0];
  gr1->setData(x, y);
  x[0] = 0.0; x[1] = 150.0;  y[0] = 50.0; y[1] = y[0];
  gr2->setData(x, y);
  customPlot->axisRect()->setupFullAxesBox();
  customPlot->xAxis->setRange(0.0, 200.0);
  customPlot->yAxis->setRange(0.0, 100.0);
skyer_ Дата 14.10.2014, 21:27
  Приветствую, нужен совет как нарисовать горизонтальные гистограммы на qcustomplot.
_Vitaliy_ Дата 1.9.2014, 14:52
  спасибо, честно говоря 17 сообщение я написал не видя Вашего 16, в котором Вы подробно все расписали, а в 18 сообщении вы меня просто "порвали" ...
хорошего кода...
Steklova Olga Дата 1.9.2014, 14:15
  я смотрела "твой" проект - искуроченный тобою мой тестовый пример.
мне надоело повторять десять раз одно и то же, я уже все сказала.
запусти мой пример, но с кнопками - увидишь, что получается.
читай доку по классам. мне по работе они сейчас не нужны, я не буду в них разбираться, чтобы тебе пересказывать. точка.
_Vitaliy_ Дата 1.9.2014, 13:08
  пока не "победил" адекватное масштабирование... Вы в мой проект не заглядывали?
Steklova Olga Дата 1.9.2014, 11:12
  Насчет моего кода... Кинь на свое окно рядом с компонентом customPlot две кнопки, к их сигналам clicked() привяжи слоты, текст которых я привела. Это для зеленого графика имитация сигналов "зеленый график выбран", "отмена выбора зеленого графика". Числа 1.0, 2.0, 3.0 относятся именно к зеленому графику, когда к нему привязана моя функция этого графика.
Запускаешь. Не выбирая графиков, можно подвинуть их все вместе или отмасштабировать их все вместе.
Нажимаешь первую кнопку, видишь оцифровку зеленого графика. Например, двигаешь его. В это время остальные графики стоят на месте.
Но когда ты после этого нажимаешь вторую кнопку (как-бы снимая выделение эеленого графика), то этот зеленый график КОНЕЧНО возвращается туда, где он был до нажатия кнопок, а не остается визуально на тех пикселах, куда ты его двигал.
Потому что, пикселы пикселами, а значения-то точек зеленого графика ты не изменил.
customPlot - как прозрачный лист, на котором нарисованы графики. А когда ты одни графики привязывешь к правой оцифровке, а другие - к левой, то получаются два прозрачных листа, один неподвижный, а другой подвижный, но в окне ты видишь их оба сразу.

На твоем месте я посмотрела бы доку по классам
QCPItemPosition, QCPItemAnchor, QCPAbstractPlottable,
enum PositionType { ptAbsolute        ///< Static positioning in pixels, starting from the top left corner of the viewport/widget.
                    ,ptViewportRatio  ///< Static positioning given by a fraction of the viewport size.
                    ,ptAxisRectRatio  ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect).
                    ,ptPlotCoords     ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes).
                  };
и все же задала вопрос на родном форуме qcustomplot. Успехов.
_Vitaliy_ Дата 30.8.2014, 8:23
  Доброго времени суток.
Посмотрел Ваши решения, немного недопонял насчет использования
on_btn_green_check_clicked()
кнопок вроде как нет.
На всякий случай прикладываю свою реализацию через
 connect(ui->customPlot, SIGNAL(plottableClick(QCPAbstractPlottable*,QMouseEvent*)),
            this, SLOT(graphClicked(QCPAbstractPlottable*)));

З.ы. хотел 7Z архивом скинуть но что-то система не пропускает, тогда портянка mainwindow.cpp:

Раскрывающийся текст
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    graphics();

    connect(ui->customPlot, SIGNAL(plottableClick(QCPAbstractPlottable*,QMouseEvent*)),
            this, SLOT(graphClicked(QCPAbstractPlottable*)));

}


void MainWindow::graphics()
{
    ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
    ui->customPlot->axisRect()->setRangeDrag(Qt::Vertical);   // peremeshenie po OY
    ui->customPlot->axisRect()->setRangeZoom(Qt::Vertical);   // mashtab po OX

    ui->customPlot->addGraph(ui->customPlot->xAxis, ui->customPlot->yAxis);
    ui->customPlot->addGraph(ui->customPlot->xAxis, ui->customPlot->yAxis);
    ui->customPlot->addGraph(ui->customPlot->xAxis, ui->customPlot->yAxis);

    ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsLine);
    ui->customPlot->graph(1)->setLineStyle(QCPGraph::lsLine);
    ui->customPlot->graph(2)->setLineStyle(QCPGraph::lsLine);

    ui->customPlot->graph(0)->setPen(QPen(Qt::red, 3));
    ui->customPlot->graph(1)->setPen(QPen(Qt::yellow, 3));
    ui->customPlot->graph(2)->setPen(QPen(Qt::green, 3));

    ui->customPlot->xAxis->setVisible(true);
    ui->customPlot->yAxis->setVisible(false);
    ui->customPlot->xAxis2->setVisible(false);
    ui->customPlot->yAxis2->setVisible(false);

    ui->customPlot->xAxis->setBasePen(QPen(Qt::black));
    ui->customPlot->yAxis->setBasePen(QPen(Qt::black));
    ui->customPlot->xAxis2->setBasePen(QPen(Qt::black));
    ui->customPlot->yAxis2->setBasePen(QPen(Qt::black));

    QVector<double> x(250), y1(250), y2(250), y3(250);
    for (int i=0; i<250; ++i)
    {
        x[i] = i;
        y1[i] = sin(x[i]/10);
        y2[i] = sin(x[i]/7) + 1.0;
        y3[i] = cos(x[i]/5) + 2.0;
    }

//    connect(ui->customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->xAxis2, SLOT(setRange(QCPRange)));
//    connect(ui->customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->yAxis2, SLOT(setRange(QCPRange)));

    ui->customPlot->graph(0)->setData(x, y1);
    ui->customPlot->graph(1)->setData(x, y2);
    ui->customPlot->graph(2)->setData(x, y3);

    ui->customPlot->graph(0)->setName("graph 0");
    ui->customPlot->graph(1)->setName("graph 1");
    ui->customPlot->graph(2)->setName("graph 2");

    ui->customPlot->rescaleAxes();

    ui->customPlot->replot();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::graphClicked(QCPAbstractPlottable *plottable)
{
  ui->statusBar->showMessage(QString("Clicked on graph '%1'.").arg(plottable->name()), 1000);

  qDebug() << plottable->name();


  if (plottable->name() == "graph 0")
  {
      ui->customPlot->yAxis->setVisible(true);

      ui->customPlot->graph(0)->setKeyAxis(ui->customPlot->xAxis);
      ui->customPlot->graph(0)->setValueAxis(ui->customPlot->yAxis);

      ui->customPlot->graph(1)->setKeyAxis(ui->customPlot->xAxis2);
      ui->customPlot->graph(1)->setValueAxis(ui->customPlot->yAxis2);
      ui->customPlot->graph(2)->setKeyAxis(ui->customPlot->xAxis2);
      ui->customPlot->graph(2)->setValueAxis(ui->customPlot->yAxis2);


      ui->customPlot->yAxis->setAutoTicks(false);
      ui->customPlot->yAxis->setAutoTickLabels(false);
      ui->customPlot->yAxis->setAutoSubTicks(false);
      ui->customPlot->yAxis->setTickVector(QVector<double>()
                                           << 1.0 << 2.0 << 3.0);
      ui->customPlot->yAxis->setTickVectorLabels(QVector<QString>()
                                                 << "1,0" << "2,0" << "3,0");

      ui->customPlot->rescaleAxes();
      ui->customPlot->replot();
  }

  if (plottable->name() == "graph 1")
  {
      ui->customPlot->graph(1)->setKeyAxis(ui->customPlot->xAxis);
      ui->customPlot->graph(1)->setValueAxis(ui->customPlot->yAxis);

      ui->customPlot->graph(0)->setKeyAxis(ui->customPlot->xAxis2);
      ui->customPlot->graph(0)->setValueAxis(ui->customPlot->yAxis2);
      ui->customPlot->graph(2)->setKeyAxis(ui->customPlot->xAxis2);
      ui->customPlot->graph(2)->setValueAxis(ui->customPlot->yAxis2);

  }


}


зипом получилось...
_Vitaliy_ Дата 29.8.2014, 20:14
  Отвечаю на 8 пост.
Цитата
Если ты переместишь синий график выше красного, то у синего все равно должна остаться оцифровка -150...-50?

Да, т.е. синхронно для всех графиков должен работать только "ресайз" по оси ОХ. По оси ОУ для каждого отдельного графика, т.е. выбрали график №N, отмасштабировали (при необходимости), передвинули (при необходимости) масштаб и местоположение этого графика остается неизменным до следующего его выбора.
Цитата
Ты зачем-то указываешь для первого графика customPlot->xAxis, customPlot->yAxis, для второго customPlot->xAxis2, customPlot->yAxis2. Но на картинке у тебя больше двух графиков. (xAxis, yAxis) - это оцифровка слева, (xAxis2, yAxis2) - справа.

про xAxis, yAxis, xAxis2, yAxis2 и их расположение мы в курсе.
Цитата
Судя по картинке, тебе надо, чтобы у всех графиков была оцифровка слева.

При первоначальном открытии окна с графиками видна только ось ОХ и все, при выборе произвольного графика подсвечивается ось OY выбранного графика, и масштаб оси ОУ этого графика соответствует размаху по ОУ этого графика.

на 12-13 пост, сейчас попробую поколдовать, сегодня-завтра отпишусь, но все равно спасибо за соучастие.
Steklova Olga Дата 29.8.2014, 18:05
  а для оцифровки
on_btn_green_check_clicked()
void MainWindow::on_btn_green_check_clicked()
{
    disconnect(ui->customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->xAxis2, SLOT(setRange(QCPRange)));
    disconnect(ui->customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->yAxis2, SLOT(setRange(QCPRange)));

    //все графики кроме зеленого переключаем на 2-ю неподвижную оцифровку
    ui->customPlot->graph(0)->setKeyAxis(ui->customPlot->xAxis2);
    ui->customPlot->graph(0)->setValueAxis(ui->customPlot->yAxis2);
    ui->customPlot->graph(1)->setKeyAxis(ui->customPlot->xAxis2);
    ui->customPlot->graph(1)->setValueAxis(ui->customPlot->yAxis2);

    ui->customPlot->xAxis->setBasePen(QPen(Qt::green, 2));
    ui->customPlot->yAxis->setBasePen(QPen(Qt::green, 2));

    //dop
//    ui->customPlot->yAxis->setVisible(true);
    ui->customPlot->yAxis->setAutoTicks(false);
    ui->customPlot->yAxis->setAutoTickLabels(false);
    ui->customPlot->yAxis->setAutoSubTicks(false);
    ui->customPlot->yAxis->setTickVector(QVector<double>()
        << 1.0 << 2.0 << 3.0);
    ui->customPlot->yAxis->setTickVectorLabels(QVector<QString>()
        << "1,0" << "2,0" << "3,0");
    //dop

    ui->customPlot->replot();
}
on_btn_green_uncheck_clicked()
void MainWindow::on_btn_green_uncheck_clicked()
{
    ui->customPlot->yAxis->setRange(ui->customPlot->yAxis2->range()); //можно это не делать (или делать, если нужно)

    connect(ui->customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->xAxis2, SLOT(setRange(QCPRange)));
    connect(ui->customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->yAxis2, SLOT(setRange(QCPRange)));

    //все графики кроме зеленого возвращаем на 1-ю подвижную оцифровку
    ui->customPlot->graph(0)->setKeyAxis(ui->customPlot->xAxis);
    ui->customPlot->graph(0)->setValueAxis(ui->customPlot->yAxis);
    ui->customPlot->graph(1)->setKeyAxis(ui->customPlot->xAxis);
    ui->customPlot->graph(1)->setValueAxis(ui->customPlot->yAxis);

    ui->customPlot->xAxis->setBasePen(QPen(Qt::black));
    ui->customPlot->yAxis->setBasePen(QPen(Qt::black));

    //dop
//    ui->customPlot->yAxis->setVisible(false);
    ui->customPlot->yAxis->setAutoTicks(true);
    ui->customPlot->yAxis->setAutoTickLabels(true);
    ui->customPlot->yAxis->setAutoSubTicks(true);
    //dop

    ui->customPlot->replot();
}
Просмотр темы полностью (откроется в новом окне)
RSS Текстовая версия Сейчас: 28.3.2024, 18:04