简体   繁体   English

如何根据用户输入动态更改任何物品的位置?

[英]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? 如何访问其他函数在MainWindow构造函数中声明和初始化的数据? Is there a method on ui->customPlot that will help me out here? ui-> customPlot上是否有一种方法可以帮助我?

I have the following code in my Qt MainWindow constructor: 我的Qt MainWindow构造函数中有以下代码:

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. 我希望用户能够在2x1 QTableWidget中输入数字并更改箭头指向的位置。 Ex: if the user enters 2,1 in the table, the arrow moves and points from 0,0 to 2,1. 例如:如果用户在表格中输入2,1,则箭头会移动并从0,0指向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.) (table1是我的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. 我尝试将QCPItemLine * vec1放入mainwindow.h中,但无法解决如何解决“没有合适的默认构造函数可用”错误,因为QCPItemLine构造函数依赖于仅在ui-> setupUI(this)之后可用的数据,在默认构造函数列表之后调用。

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 *'". 我还尝试在on_table1_cellChanged函数中调用QCPItemLine * vec1 = ui-> customPlot-> item(),但收到此错误:“无法从'QCPAbstractItem *'转换为'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. 另外,我知道这种方式很冒险,因为我不能总是依靠vec1作为添加到我的customPlot中的最新项。

You could make vec1 a (private) member of the class, initialize it as nullptr and set it after setupUI has been called. 您可以将vec1设为该类的(私有)成员,将其初始化为nullptr,并在调用setupUI之后进行设置。

mainWindow.h mainWindow.h

private: 
      QCPItemLine* m_vec1;

mainWindow.cpp 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 您也可以在单元格更改插槽中访问m_vec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM