【问题标题】:How do I change any item's position dynamically based on user input?如何根据用户输入动态更改任何项目的位置?
【发布时间】:2017-02-09 04:31:49
【问题描述】:

如何访问在其他函数的 MainWindow 构造函数中声明和初始化的数据? ui->customPlot 上是否有可以帮助我的方法?

我的 Qt MainWindow 构造函数中有以下代码:

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

我希望用户能够在 2x1 QTableWidget 中输入数字并更改箭头指向的位置。例如:如果用户在表格中输入 2,1,箭头会移动并从 0,0 指向 2,1。

据我所知:

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 是我的 QTableWidget 的名称。)


我尝试将 QCPItemLine* vec1 放在 mainwindow.h 中,但无法弄清楚如何解决“没有适当的默认构造函数可用”错误,因为 QCPItemLine 构造函数依赖于仅在 ui->setupUI( this),在默认构造函数列表之后调用。

我还尝试在 on_table1_cellChanged 函数中调用 QCPItemLine* vec1 = ui->customPlot->item(),但收到此错误:“无法从 'QCPAbstractItem *' 转换为 'QCPItemLine *'”。另外我知道这种方式是有风险的,因为我不能总是依赖 vec1 作为添加到我的 customPlot 中的最新项目。

【问题讨论】:

    标签: c++ qt data-structures window qcustomplot


    【解决方案1】:

    您可以使 vec1 成为该类的(私有)成员,将其初始化为 nullptr 并在调用 setupUI 后设置它。

    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 也可以在你的 cell-changed-slot 中访问

    【讨论】:

    • 如果我在 mainWindow.h 中说private QCPItemLine* vec1 = NULL;,那会解决“没有合适的默认构造函数可用”吗?
    • 你不能在你的类定义中初始化你的(非静态)成员。您声明它,在初始化列表中对其进行初始化,并在 setupUI 被调用后实例化您的对象。
    • 很好,有道理。谢谢。
    猜你喜欢
    • 2011-01-14
    • 2020-12-03
    • 2017-06-08
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2013-01-31
    相关资源
    最近更新 更多