[solved] QObject: invalid conversion issue.
-
Good day everyone
I have an issue that is probably related to me not using pointers and classes correctly. I am stuck and I would really appreciate some help.
I have a book class, that is derived from QObject:
@
class book : public QObject
{
Q_OBJECT
public:
//Default constructor.
explicit book(QObject *parent = 0);
//Constructor.
book(QString a, QString t, double c);
//Retrieve values in string format.
QString toString() const;
//Getters.
QString getAuthor() const;
QString getTitle() const;
double getCost() const;private:
//Data members.
QString author;
QString title;
double cost;
};
@Now I have a library class, that keeps a QList of books:
@
class library
{
public:
//Default constructor.
library();
//Add a book to the list of books.
void addBook(book *b);
//Return a list of all the books.
QStringList getBookList() const;
//Destructor.
~library();private:
//Member to contain books.
QList<QObject *> libraryBooks;
};
@My error is in the getBookList() function. Here is the code:
@
//Return a list of all the books.
QStringList library::getBookList() const{
QStringList bookList;
QString entry;
book *myBook;
foreach(myBook, libraryBooks){
entry = myBook->toString();
bookList << entry;
}
return bookList;
}
@The error that I get is "invalid conversion from 'QObject*' to 'book*'[-fpermissive]
What gets me is that book is derived from QObject, so that shouldn't be a problem?
Any ideas?Thank you
[edit: added missing coding tags @ SGaist]
-
Hi and welcome to devnet,
libraryBooks is a QList of QObject * which is not the same thing as a QList of book * so you shoulde either:
- Use a QList<book *>
- Use qobject_cast in your loop
e.g.
@
foreach(QObject *book, libraryBooks){
book entry = qobject_cast<book>(book);
bookList << entry->toString();
}
@But the first question is: does it really make sense to store your books as a list of QObject * rather than book * ?
-
You're welcome !
Since you have your library running, please update the thread title perpending [solved] so other forum users may know a solution has been found :)