views:

151

answers:

1

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?

+1  A: 

Actually, your solution is already almost there. In fact, qobject_cast will return NULL if it can't perform the cast. So try it on one of the classes, if it's NULL, try it on the other:

QString text;
QTextEdit *textEdit = qobject_cast<QTextEdit*>(sender);
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender);
if (textEdit) {
    text = textEdit->toPlainText();
} else if (lineEdit) {
    text = lineEdit->text();
} else {
    // Return an error
}
Adam Batkin
Thanks, works great!
synchronicity