确定 Qt 中的对象类型
我有一系列 QTextEdits 和 QLineEdits 通过 QSignalMapper 连接到插槽(它发出 textChanged(QWidget*) 信号)。当调用连接的插槽时(粘贴在下面),我需要能够区分两者,以便我知道是否调用 text() 或 toPlainText() 函数。确定 QWidget 子类类型的最简单方法是什么?
void MainWindow::changed(QWidget *sender)
{
QTextEdit *temp = qobject_cast<QTextEdit *>(sender);
QString currentText = temp->toPlainText(); // or temp->text() if its
// a QLineEdit...
if(currentText.compare(""))
{
...
}
else
{
...
}
}
我正在考虑使用 try-catch 但 Qt 似乎对异常没有非常广泛的支持......有什么想法吗?
I have a series of QTextEdits and QLineEdits connected to a slot through a QSignalMapper(which emits a textChanged(QWidget*) signal). When the connected slot is called (pasted below), I need to be able to differentiate between the two so I know whether to call the text() or toPlainText() function. What's the easiest way to determine the subclass type of a QWidget?
void MainWindow::changed(QWidget *sender)
{
QTextEdit *temp = qobject_cast<QTextEdit *>(sender);
QString currentText = temp->toPlainText(); // or temp->text() if its
// a QLineEdit...
if(currentText.compare(""))
{
...
}
else
{
...
}
}
I was considering using try-catch but Qt doesn't seem to have very extensive support for Exceptions... Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,你的解决方案已经差不多了。事实上,
qobject_cast
将返回如果无法执行转换,则为 NULL
。因此,在其中一个类上尝试,如果它为 NULL,则在另一个类上尝试:Actually, your solution is already almost there. In fact,
qobject_cast
will returnNULL
if it can't perform the cast. So try it on one of the classes, if it'sNULL
, try it on the other:您还可以使用 sender->metaObject()->className() 这样就不会进行不必要的转换。特别是如果您有很多课程要测试。代码将是这样的:
我知道这是一个老问题,但我留下这个答案以防万一它对某人有用......
You can also use sender->metaObject()->className() so you won't make unnecesary casts. Specially if you have a lot of classes to test. The code will be like this:
I know is an old question but I leave this answer just in case it would be useful for somebody...