Search code examples
c++qtdata-structureswindowqcustomplot

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


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?

I have the following code in my Qt 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.


Solution

  • You could make vec1 a (private) member of the class, initialize it as nullptr and set it after setupUI has been called.

    mainWindow.h

    private: 
          QCPItemLine* m_vec1;
    

    mainWindow.cpp

    MainWindow::Mainwindow(QWidget* parent):
        QMainWindow(parent),
            m_vec1(nullptr)
            {
                ui->setupUi(this);
                m_vec1 = new QCPItemLine(ui->mainGraph);
            }
    

    m_vec can also be accessed in your cell-changed-slot