在类之间传输数据

时间:2014-06-09 23:59:17

标签: c++ qt class

我的代码以这种方式设置:带有QTableWidget的主窗口,以及使用与MainWindow不同的类创建的控制面板。在控制面板控件中有一个QListWidget,我想从表中加载标题的标题,但是QTableWidget是私有的,我如何在两个类之间传递数据?

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "QControlPanel.h"
#include <QMainWindow>
#include <QWidget>
#include <QtGui>
#include <QTableWidget>


namespace Ui {
    class MainWindow;
    class GenerateXML;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

    ~MainWindow();

public slots:

private:
    Ui::MainWindow *ui;
    QTableWidget* m_pTableWidget;
    QControlPanel* preferences;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{

    this->setWindowIcon(QIcon("DrawItem.ico"));
    this->setWindowTitle("DrawItem");
    resize(890, 475);

    m_pTableWidget = new QTableWidget(this);
    m_TableHeader<<"A"<<"B"<<"C"<<"D"<<"E";
    m_pTableWidget->setHorizontalHeaderLabels(m_TableHeader);
    m_pTableWidget->resizeColumnsToContents();
    m_pTableWidget->verticalHeader()->setVisible(false);
    m_pTableWidget->move(30, 75);
    m_pTableWidget->resize(410, 151);

    preferences = new QControlPanel(this);
}

QControlPanel.h

#include <QDialog>
#include <QTableWidget>

#ifndef QCONTROLPANEL_H
#define QCONTROLPANEL_H

class QControlPanel : public QDialog
{
    Q_OBJECT

public:
    explicit QControlPanel(QWidget *parent = 0);

    ~QControlPanel();

public slots:
    void customHeader(QTableWidget *table);

private:
    QListWidget *headerlist;

private slots:

};

#endif

QControlPanel.cpp

#include "QControlPanel.h"

QControlPanel::QControlPanel(QWidget *parent) :
    QDialog(parent)
{
    headerlist = new QListWidget(inputHeader);
    headerlist->setGeometry(140, 15, 140, 130);
}

1 个答案:

答案 0 :(得分:0)

您可以在QControlPanel类中有一个信号来检索标题。所以QControlPanel可以是:

class QControlPanel : public QDialog
{
    Q_OBJECT

public:
    explicit QControlPanel(QWidget *parent = 0);

    ~QControlPanel();

signals:

    QStringList getHeaders();

private:
    QListWidget *headerlist;
};

并将getHeaders()信号连接到类的插槽,该插槽包含要检索它们的列列表。这应该在MainWindow

的构造函数中完成
connect(preferences,SIGNAL(getHeaders()),this,SLOT(getTableHeader()));

getTableHeader()MainWindow中的一个插槽,它返回标题列:

QStringList getTableHeader()
{
    return m_TableHeader;
}

现在您可以访问QControlPanel中的标题:

QControlPanel::QControlPanel(QWidget *parent) :
    QDialog(parent)
{
    headerlist = new QListWidget();
    headerlist->insertItems(0, getHeaders());
}