QPlainTextEdit 分段错误
我在选项卡小部件中有一些带有 QPlainTextEdit 的 Qt 应用程序。当尝试在其上创建指针
QPlainTextEdit *w = (QPlainTextEdit*)ui->tabWidget->widget(0)
并调用 document() 方法
w->document()
时,我遇到了段错误。
但如果我直接调用文档,例如 ui->mainEdit->document(),那么一切正常。
有人能解释一下为什么会发生吗?
I have some Qt application with QPlainTextEdit in Tab widget. When try to make a pointer on it
QPlainTextEdit *w = (QPlainTextEdit*)ui->tabWidget->widget(0)
and call a document() method
w->document()
I get a segfault.
But if i call document directly, e.g. ui->mainEdit->document(), then everything works fine.
Can anybody explain me why it happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想做的事:
然后 w->document() 将返回你想要的。您遇到分段错误,因为当您投射 ui->tabWidget->widget(0); 时给出一个指向选项卡页对象的指针。当您将其转换为 QPlainTextEdit* 时,将告诉您的程序将不代表 QPlainTextEdit 的内存部分视为 QPlainTextEdit。这会在您调用 w->document() 时引起麻烦,因为它尝试访问的内存位置不是它所期望的属于 QPlainTextEdit 的内存位置。
You want to do:
Then w->document() will return what you want. You are getting the segmentation fault because when you cast 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. 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.
我几乎可以肯定,
ui->tabWidget->widget(0)
返回 tabWidget 内的容器小部件。尝试 qDebug() << ui->tabWidget->widget(0)->metaObject()->className() 并查看打印内容。它可能只是“QWidget”而不是“QPlainTextEdit”。您的编辑位于此小部件的布局内i'm almost sure, that
ui->tabWidget->widget(0)
return container widget inside of tabWidget. TryqDebug() << ui->tabWidget->widget(0)->metaObject()->className()
and see what is printed. It's probably just "QWidget" not "QPlainTextEdit". Your edit is inside of layout of this widget您可以使用 qobject_cast 确保它返回正确的类型。
如果类型不是 QPlainTextEdit* 则返回 0。
如前所述, widget(0) 可能不会返回您想要的内容 - 并且可能包含容器或其他一些项目,并且可能不是您想要访问小部件的方式,除非没有其他方法。
You can use qobject_cast to make sure that it returns the right type.
It'll return 0 if the type is not of QPlainTextEdit*.
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.