How to connect signals and slots inside QObject subclass?
-
Hello everyone)
Currently I'm trying to implement simple chess board but I stuck on on a proble I don't know how to solve:I have a class - BoardController and I'm trying to connect its slot to view's signal but it seems it doesn't happen - slot is never called.
When I perform connection directly in main method it works fine and slot is being called.Would you please tell me what is wrong with my code?
Thanks in advance)
BoardController.h
class BoardController : public QObject, protected Controller { Q_OBJECT protected: QObject* boardView; Board& boardModel; public: BoardController(QQmlEngine& engine, QObject* _boardView, Board& _boardModel); virtual ~BoardController(){} void start(); void move(int fromRow, int fromCol, int toRow, int toCol); public slots: void movePiece(int fromRow, int fromCol, int toRow, int toCol); };
BoardController.cpp
BoardController::BoardController(QQmlEngine& _engine, QObject* _boardView, Board& _boardModel) :Controller(_engine), boardView(_boardView), boardModel(_boardModel) { } void BoardController::start() { if(boardView) { // I'm sure the control reaches this point // but movePiece slot is never called when I perform connection inside this class connect(boardView, SIGNAL(movePiece(int, int, int, int)), this, SLOT(movePiece(int, int, int, int))); } QQmlContext* context = engine.rootContext(); if(context) { context->setContextProperty("myBoardModel", QVariant::fromValue(boardModel.getListModel())); } } void BoardController::move(int fromRow, int fromCol, int toRow, int toCol) { boardModel.move(fromRow, fromCol, toRow, toCol); } void BoardController::movePiece(int fromRow, int fromCol, int toRow, int toCol) { boardModel.move(fromRow, fromCol, toRow, toCol); }
-
Hi,
You should rather do the connections in the constructor otherwise you are going to have several connections since you are adding one each time you call start.
-
@diredko Qt will output signal/slot problems on the console. Run your application from the console and you should see something like:
QObject::connect: No such slot QObject::movePiece(int, int, int, int)
Or something similar if there is an issue.
Also you can add a
qDebug() << "Got here"
to yourconnect()
but like @SGaist said, you are connecting in a bad place. qDebugs() will show up on the console as well.If you are in windows you will have to add
CONFIG += console
to your project file. Linux and OSX should be fine without.And finally add
qDebug()
messages to yourmove
andmovePiece
to see if it's getting in there.Or of course you could use the debugger for all this. ;)