简体   繁体   English

QPlainTextEdit分段错误

[英]QPlainTextEdit segmentation fault

I have some Qt application with QPlainTextEdit in Tab widget. 我在Tab小部件中有一些带有QPlainTextEdit的Qt应用程序。 When try to make a pointer on it 尝试在其上建立指针时

QPlainTextEdit *w = (QPlainTextEdit*)ui->tabWidget->widget(0)

and call a document() method 并调用document()方法

w->document()

I get a segfault. 我遇到了段错误。

But if i call document directly, eg ui->mainEdit->document(), then everything works fine. 但是,如果我直接调用文档,例如ui-> mainEdit-> document(),则一切正常。

Can anybody explain me why it happens? 谁能解释我为什么会这样?

You want to do: 您想做:

QPlainTextEdit *w = ui->mainEdit;

Then w->document() will return what you want. 然后w-> document()将返回您想要的内容。 You are getting the segmentation fault because when you cast ui->tabWidget->widget(0); 出现分段错误是因为当您投射ui-> tabWidget-> widget(0); gives a pointer to a tab page object. 提供指向选项卡页对象的指针。 When you cast this to QPlainTextEdit* are telling your program to treat a part of memory that does not represent a QPlainTextEdit as a QPlainTextEdit. 当将其强制转换为QPlainTextEdit *时,就是告诉程序将不代表QPlainTextEdit的一部分内存视为QPlainTextEdit。 This causes trouble at the time that you call w->document() because that is in the memory location that it tries to access is not what it would expect from memory which belongs to QPlainTextEdit. 在您调用w-> document()时,这会引起麻烦,因为它试图访问的内存位置与QPlainTextEdit的内存不符。

i'm almost sure, that ui->tabWidget->widget(0) return container widget inside of tabWidget. 我几乎可以确定, ui->tabWidget->widget(0)返回tabWidget内的容器小部件。 Try qDebug() << ui->tabWidget->widget(0)->metaObject()->className() and see what is printed. 尝试qDebug() << ui->tabWidget->widget(0)->metaObject()->className()并查看打印的内容。 It's probably just "QWidget" not "QPlainTextEdit". 它可能只是“ QWidget”而不是“ QPlainTextEdit”。 Your edit is inside of layout of this widget 您的编辑位于此小部件的布局内

You can use qobject_cast to make sure that it returns the right type. 您可以使用qobject_cast来确保它返回正确的类型。

QPlainTextEdit *w = qobject_cast<QPlainTextEdit*>(ui->tabWidget->widget(0));
if (w)
{
...
}

It'll return 0 if the type is not of QPlainTextEdit*. 如果类型不是QPlainTextEdit *,它将返回0。

As stated, widget(0) is probably not returning what you wanted - and probably contains a container or some other item, and is probably not the way you want to be accessing your widgets unless there is no other way. 如前所述,widget(0)可能不会返回您想要的内容-可能包含容器或其他项目,并且除非没有其他方法,否则可能不是您想要访问小部件的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM