我从另一个类(带有实例)访问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
}
答案 0 :(得分:0)
您正在投射QApplication::instance()
,这是源自QApplication *
QCoreApplication *
的{{1}} QObject *
。这不起作用,它不是secondWindow *
,甚至不是QMainWindow *
,甚至不是QWidget *
。
除此之外,您的编码风格相当奇怪 - 在Qt中,习惯使用CamelCase
用于类,而不是thisStuff
通常适用于函数和方法。包括<read.moc>
是错误的。为什么read::m_read
是静态的?最后,两个窗口类之间的耦合是以一种奇怪的方式建立的(访问像QApplication
这样的全局内容只是为了获得对另一个窗口的引用,这些代码都是丑陋的代码)。一种更好,更明显的方法是将所有窗口包装在父对象中或明确设置依赖关系,可能是这样的:
MainWindow *mainWindow = new MainWindow();
SecondWindow *second = new SecondWindow(mainWindow);
UtilityWindow *utilityWin = new UtilityWindow(second);