在QT中在两个QWidget表单之间传递参数

时间:2013-05-31 09:37:40

标签: qt parameter-passing qwidget

我是QT的新手,我正试图在两种形式之间传递一个参数,但我无法做到这一点。可以通过给我一个传递字符串常量“参数的简单示例来帮助我“从主窗口到另一个名为结果的QWidget 0窗口

2 个答案:

答案 0 :(得分:1)

我不确定你在这里问的是什么,因为我觉得这很简单,但这里是头文件的完整代码:

#ifndef CMAINWINDOW_H
#define CMAINWINDOW_H

#include <QDialog>
#include <QLabel>
#include <QPushButton>

/* this is your dialog with results.
   It contains one label to show the value of parameter passed in. */
class CResults : public QDialog
{
    Q_OBJECT

  public:
    CResults(const QString & text = QString(), QWidget *parent = 0);

    void setText(const QString & text);

  private:
    QLabel *m_lbl;
};

/* This is your main top-level window which contains two push buttons.
   Each of them triggers one dialog and passes a different parameter to it. */
class CMainWindow : public QWidget
{
    Q_OBJECT

  public:
    CMainWindow(void);


  private slots:
    void onDialog1BtnClick(void);
    void onDialog2BtnClick(void);

  private:
    QPushButton *m_pb_dlg1;
    QPushButton *m_pb_dlg2;
    CResults *m_dlg1;
    CResults *m_dlg2;
};

#endif // CMAINWINDOW_H

这是实施:

#include "CMainWindow.h"

#include <QVBoxLayout>

CResults::CResults(const QString & text, QWidget *parent)
  : QDialog(parent)
{
  m_lbl = new QLabel(text, this);
}

void CResults::setText(const QString & text)
{
  m_lbl->setText(text);
}


CMainWindow::CMainWindow(void)
 : QWidget(0)
{
  /* The following line shows one way of passing parameters to widgets and
     that is via constructor during instantiation */
  m_dlg1 = new CResults("parameter", this);
  m_dlg2 = new CResults(QString(), this);
  m_pb_dlg1 = new QPushButton("Dialog1", this);
  connect(m_pb_dlg1, SIGNAL(clicked()), SLOT(onDialog1BtnClick()));
  m_pb_dlg2 = new QPushButton("Dialog2", this);
  connect(m_pb_dlg2, SIGNAL(clicked()), SLOT(onDialog2BtnClick()));

  QVBoxLayout *l = new QVBoxLayout(this);
  l->addWidget(m_pb_dlg1);
  l->addWidget(m_pb_dlg2);

  setLayout(l);
}

void CMainWindow::onDialog1BtnClick(void)
{
  m_dlg1->exec();
}

void CMainWindow::onDialog2BtnClick(void)
{
  /* In this case you want to override the default value passed to constructor,
     so you will use the setter function */
  m_dlg2->setText("Something random");
  m_dlg2->exec();
}

如果您有其他意思,请更具体,以便我可以调整我的答案。

答案 1 :(得分:0)

你需要创建一个新类,让我们说MyWidget,从QWidget或QDialog派生,你想要它,在其中创建插槽 - setText(QString txt)或者你喜欢。然后在MainWindow类中,创建MyWidget -

的instange
... code that leads to moment, where you want to create another widget
MyWidget* wg=new MyWidget();
wg->setText("And that's all the magic"); // you pass text to that widget's slot setText(), where you use it however you like

修改

要在标签中显示文字,班级setText(QString txt)中的广告单MyWidget应该是这样的:

MyWidget::setText(QString txt){
    myLabel->setText(txt); // myLabel is Qlabel, that you created in MyWidget class    
}