QCustomPlot Discussion and Comments

How do I change any item's position dynamically based on user input?Return to overview

I have the following code in the MainWindow constructor:

QCPItemLine* vec1 = new QCPItemLine(ui->mainGraph);
vec1->start->setCoords(0, 0);
vec1->end->setCoords(4, 4);

I want the user to be able to enter numbers into a 2x1 QTableWidget and change where the arrow points. Ex: if the user enters 2,1 in the table, the arrow moves and points from 0,0 to 2,1.

This is as far as I have gotten:

void MainWindow::on_table1_cellChanged(int row, int column)
    // how can I access vec1 from here, since it is declared only in the scope of the constructor?

(table1 is the name of my QTableWidget.)


I tried putting QCPItemLine* vec1 in mainwindow.h but couldn't figure out how to resolve the "No appropriate default constructor available" error, seeing as the QCPItemLine constructor relies on data that is only available after ui->setupUI(this), which is called after the default constructor list.

I also tried calling QCPItemLine* vec1 = ui->customPlot->item() in the on_table1_cellChanged function, but got this error: "cannot convert from 'QCPAbstractItem *' to 'QCPItemLine *'". Plus I know that way is risky, because I can't always rely on vec1 being the most recent item added to my customPlot.


TL;DR: How can I access data that is declared and initialized in the MainWindow constructor in other functions? Is there a method on ui->customPlot that will help me out here?

it sounds like you are new to c++. the 'cannot convert from...' error is easily fixed by using dynamic_cast. Also when you put a pointer in the header file, it shouldnt be default constructing to anything but undefined memory... as long as you use new and create the object after you have called setupUi, it should be fine. (dont try to define it in your header file, just declare it).

it looks like your plot is actually ui->mainGraph and not ui->customPlot.
if you put QCPItemLine * vec1; in the header file, you would need to either include qcustomplot.h or you would need to use a forward declare: class QCPItemLine;

Gotcha, I'll read up on dynamic_cast.

How exactly would forward declaring help?

i was just pointing out that if you put a member variable of a class type into a header file ,you need to either include the header file that describes the class or forward declare the class.