(Qt) Read access error when attempting to use any function from another widget class on my MainWindow

孤者浪人 提交于 2020-01-06 08:49:11

问题


I'd like to access some functions of a dialog-type widget from my mainwindow.cpp.

I've created a simple function in the widget class that returns an int, which looks like this:

dialog.h:

 public:  
      int getRowCountData();

dialog.cpp:

 int Dialog::getRowCountData()
 {
      return ui->tableWidget->rowCount();
 }

Usage:

my mainWindow.h:

private:
    Dialog *dialog;

my mainwindow.cpp:

dialog = new Dialog;


int count = dialog->getRowCountData();   <<<<<--------------this throws a read access error!

code: 0xc0000005 read access violation at: 0x0 flas=0x0

how am I to use another widget's public functions such as this simple one?

I must not be referencing the integer I'd like to set using the rowcount function. Signals and slots have worked great for me in the past when using them to transfer data between widgets, but I'd like to stick to using my dialog widget's function like this if I can.

I came about this method for retrieving data on my other widget by posting this question: AccessingQTableWidget's data from another class. @Chernobyl maybe you have some further insight to provide?

Thanks in advance!


回答1:


No. Problem in usingwrong pointer. This execption means exactly this.

Check is dialog pointer isn't null and maybe ui->tableWidget doesn't exist. You should call setupUi if you want use widgets which created in Qt Designer

Write this:

if(!dialog)
qDebug() << "fail";
else
{qDebug() << "good";//your call}

Most times such a crash happens is caused by

  • deleting an object more than once
  • accessing a dangling pointer (i.e. a pointer to an already deleted object)
  • accessing a null pointer


来源:https://stackoverflow.com/questions/25901888/qt-read-access-error-when-attempting-to-use-any-function-from-another-widget-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!