简体   繁体   中英

Use variable declared in MainWindow Qt

I have the following problem in Qt, I'm trying to make a chess-game and I'm encountering some problems:

In the class mainwindow I have the following function:

    MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    scene = new ChessBoard;
    QGraphicsView *view = new QGraphicsView(scene);
    setCentralWidget(view);
    connect(scene,SIGNAL(clicked(int,int)),this,SLOT(clicked(int,int)));

    //!!!!!!!!!!
    scene->setInitialPositions();
}

I have a variable scene, scene is an object of the class ChessBoard. In the whole class mainwindow I can use the scene-variable to use functions declared in ChessBoard.

功能实例

However, I have another class called game . In game I have this function

void game::setStartBord() {
   scene->setInitialPositions();
}

It simply needs to launch scene->setInitialPositions();

However, I don't have access to the 'scene-variable' there. I tried to inherit the ChessBoard and MainWindow class, tried to make scene global, but none really were a good solution.

How would I do that? Full code is visibly here: https://github.com/UA-Niel/chess

You can use signal and slot technique. Connect your game class object to scene object.

connect(game, &Game::mySignal, scene, &ChessBoard::setInitialPositions);

Define in your Game-Class the signal.

class Game .. {

.. 

signals: 
void mySignal();

..
};

Then define setInitialPositions in your ChessBorard class in public slots.

class ChessBoard {

...

public slots:
   <datatype> setInitialPositions();

};

Then use

emit mySignal(); from Game class

to execute setIntialPositions() in your ChessBoad class.

You need to design your code that you have access to both objects at some point. Mostly this is MainWindow because you intialize classes upon program start.

If your code does not depend on the intialized class. You can simply do a new ChessBoard object in Game class

ChessBoard myObject;
myObject.setIntialPositions();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM