PDA

View Full Version : type QWidget is not a direct base of MyWidget



eLancaster
4th December 2010, 13:10
Hi there.
I'm folloiwng the Qt Tutorials from the Qt website (if anyone knows of better tutorials, please tell me the link).

I wrote this code on QtCreator and it gave me an error



class MyWidget : public QMainWindow
{
Q_OBJECT

public:
explicit MyWidget(QWidget *parent = 0);
~MyWidget();

private:
Ui::MyWidget *ui;
};

MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)//ERROR
{
QPushButton *quit = new QPushButton("Close Application", this);
quit->setGeometry(150,150,100,100);
quit->setFont(QFont("Times",12,QFont::Bold));

connect(quit,SIGNAL(clicked()),qApp,SLOT(quit()));

}



Error: Type "QWidget" is not direct base of 'MyWidget'.

Could someone tell me where I've gone wrong - thanks!

Zlatomir
4th December 2010, 13:41
You derived your MyWidget class from QMainWindow class, in this code:


class MyWidget : public QMainWindow //QMainWindow is the base class of MyWidget
{
//...

So you will need to pass the parent to the QMainWindow constructor:

MyWidget::MyWidget(QWidget *parent)
: QMainWindow(parent)//No ERROR now

eLancaster
4th December 2010, 15:12
Believe me when I say this - you just made my day!!!
THANK YOU!!!!!!!!

Added after 4 minutes:

Oh but there is one more thing, now that the code actually runs - when I click on the close application button - it doesn't work. Is there something wrong with the signals and slots?
and just one last quesiton - we write the constructor definition in the mywidget.cpp file, right?

johnc
4th December 2010, 21:06
I would do the following:

connect(quit, SIGNAL(clicked()), this, SLOT(close()));

This will close the main window, which will in turn exit the main application, as your widget is probably blocking the main event loop (which is probably why calling the quit() slot is not currently working).

I would make it a habit of placing debug assertions on your connect statements as well:

bool ok = connect(...);
Q_ASSERT(ok);

This will save you trouble when you mistype something to connect, and alert you immediately of the mistake.

As far as your constructor going in the .cpp file - I always place implementation code (such as constructor definitions) in a .cpp file, as it allows more flexibility in your code. Unless the code is doing something really, really simple, like only returning a primitive data type or you are doing something like writing a template.

eLancaster
4th December 2010, 21:16
Oh yeah - using this, that shoulda been obvious!

Thanks alot about the Q_assert tip - This is my complete first deep doing this GUI stuff so I really appreciate it!