存储对话框中的变量并在qvtkwidget中使用它



我创建了一个对话框,在其中我要求一些切片的长度,比如xmax、ymax和zmax作为切片的数量。我打算在qvtkwidget的主窗口中使用这些数字。我将简化并使示例仅为一个变量,这样您就可以理解并帮助我。

这是我的对话.cpp

#include <QtGui/QApplication>
#include <QDir>
#include <iostream>
using namespace std;
#include "dialog.h"
#include "ui_dialog.h"
// Create getters to transfer variables to main.cpp
double Dialog::getxpax()
{
    return xpax;
}
// Start the mainwindow
void Dialog::startplanevolume()
{
  // Getting some proprieties for the lenght of the volume
    QString XMAX=ui->lineEdit->text();
    xpax=XMAX.toDouble();
    if (xpax==0)
    {
        ui->label_17->setText("Error: Can't start, invalid nmeasures");
        ui->label_17->setStyleSheet("QLabel { color : red; }");
    }
    else
    {
        this->accept();        
    }
}
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
  // Control volume measures
    // Making the lineedit objects only accept numbers
    ui->lineEdit->setValidator(new QDoubleValidator(this));
  // Start planevolume
    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(startplanevolume()));
    connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(hide()));
}

按钮为ok按钮,按钮_2为取消按钮。

在我的主窗口中,我创建了一个setter函数来设置xmax的值。

这是一些代码。

// Get stored data from dialog
void planevolume::setxpax(double xpax)
{
    xp=xpax;
}

当我使用qDebug()时,setter中的xp会向我显示xp实际上获得了xpax值。

这是我的主.cpp

#include <QtGui/QApplication>
#include <iostream>
using namespace std;
#include "planevolume.h"
#include "dialog.h"
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Dialog *dialog= new Dialog;
    if (dialog->exec())
    {
        planevolume mainwindow;
        mainwindow.setxpax(dialog->getxpax());
        mainwindow.show();
        return app.exec();
    }
return 0;
}

所以唯一的问题是,在这里,当我需要的时候,在主窗口作为planevolume.cpp,值还没有设置,

planevolume::planevolume(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::planevolume)
{
    ui->setupUi(this);
// My vtk statements are here in the code, but they are 
// executed before the setter gives the value to my new 
// variable xp, so when I need the value it has not been set yet.

有什么想法吗?

如果planevolume构造函数需要这些数据,可以将它们作为参数传递给构造函数本身(您也可以使对话框返回结构中的所有变量,使其具有一个要传递的参数,而不是每个参数都有一个访问器)。

另一种解决方案是在事件循环开始后调用vtk部分,将其放入插槽中,并用QTimer::singleShot调度其执行。

在最后一种情况下,您的代码应该是这样的:

planevolume::planevolume(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::planevolume)    
{
    ui->setupUi(this);
    QTimer::singleShot(0, this, SLOT(setupVtk()));
}
// declared as a slot in the class
void planevolume::setupVtk() 
{
    // Your VTK statements would be here
}

最新更新