0

我在从另一个类(带有实例)访问 ui 元素时遇到问题。我的应用程序中有第二个 QMainWindow,我可以在 secondWindow.cxx 类中访问所有 ui 元素,但不能在 read.cxx 类中访问。我的代码如下所示。我的错误在哪里?谢谢您的帮助。

-------------------------------secondWindow.h------------------------------------

#ifndef __secondWindow_h
#define __secondWindow_h

#include "ui_secondwindow.h"

class secondWindow : public QMainWindow
{
    friend class read;
    igstkStandardClassBasicTraitsMacro(secondWindow, QMainWindow);
    Q_OBJECT

public:
    igstkStateMachineMacro();

    secondWindow();
    virtual ~secondWindow();
    void createSignalAndSlots();

public slots:
    void secondWindowTest();

protected:

private:
    Ui::secondMainWindow m_secondWindowUI;
};
#endif

-------------------------------secondWindow.cxx------------------------------------

#include "secondWindow.moc"
#include "secondWindow.h"
#include "read.h"

secondWindow::secondWindow() :m_StateMachine(this)
{
    m_secondWindowUI.setupUi(this);
    createSignalAndSlots();
}

void secondWindow::createSignalAndSlots()
{
    connect(m_secondWindowUI.pushButton1, SIGNAL(clicked()),this, SLOT(secondWindowTest()));

    connect(m_secondWindowUI.pushButton2, SIGNAL(clicked()), read::instance(), SLOT(readTest()));
}

void secondWindow::secondWindowTest()
{
    m_secondWindowUI.pushButton1->setEnabled(true); //OK
}

secondWindow::~secondWindow(){}


---------------------------------read.h--------------------------------------

#pragma once

#include "secondWindow.h"

class read : public QObject
{
    Q_OBJECT

public:
    static read *instance();
    read();
    virtual ~read() {}

public slots:
    void readTest();

protected:
    secondWindow    *m_readUI;
    static read     *m_read;

private:
};

---------------------------------read.cxx--------------------------------------
#include <read.moc>
#include "secondWindow.h"
#include "read.h"

read *read::m_read= NULL;

read::read()
{
    m_readUI = dynamic_cast<secondWindow*>( QApplication::instance() );
}

read *read::instance()
{
    if(m_read == NULL)
    m_read = new read();

    return m_read;
}

void read::readTest()
{
    m_readUI->m_secondWindowUI.qlabelTest->setText("test"); //segmentation fault
}
4

1 回答 1

0

您正在铸造 a QApplication::instance(),这是QApplication *QCoreApplication *派生 派生的QObject *。那是行不通的,它不是 a secondWindow *,甚至不是 a ,甚至QMainWindow *不是 a QWidget *

除此之外,您的编码风格相当奇怪——在 Qt 中,习惯上CamelCase用于类,而不是thisStuff通常适用于函数和方法。包括<read.moc>是错误的。为什么是read::m_read静态的?最后,两个窗口类之间的耦合是以一种奇怪的方式建立的(访问全局的东西,比如QApplication只是为了获得对另一个窗口的引用,代码很难看)。一种更好更明显的方法是将所有窗口包装在父对象中或显式设置依赖关系,可能像这样:

MainWindow *mainWindow = new MainWindow();
SecondWindow *second = new SecondWindow(mainWindow);
UtilityWindow *utilityWin = new UtilityWindow(second);
于 2013-04-11T21:11:44.393 回答