0

我是 QT 的新手,我正在尝试在两种形式之间传递一个参数,但我无法做到这一点..谁能帮我,给我一个简单的例子,从 main 传递一个字符串常量“参数”窗口到另一个称为结果的 QWidget 0 窗口

4

2 回答 2

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();
}

如果你的意思是别的,请更具体,以便我调整我的答案。

于 2013-05-31T10:42:10.243 回答
0

您需要创建一个新类,比如说MyWidget,从 QWidget 或 QDialog 派生,您希望它如何,在其中创建插槽 -setText(QString txt)或者您喜欢的任何方式。然后在您的 MainWindow 类中,创建实例MyWidget-

... 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    
}
于 2013-05-31T10:56:54.607 回答