幾天前我剛開始學習Qt來製作一款遊戲,而我試圖弄清楚如何讓佈局工作。Qt - QStackedLayout setCurrentIndex顯示空白窗口而不是部件
我想要的是一個使用QStackedLayout和2個窗口小部件的窗口:StartScreen和GameScreen。 StartScreen顯示在程序運行的頂部。 StartScren中的一個按鈕連接到Window中的一個函數,Window將調用setCurrentIndex來將小部件更改爲GameScreen。
現在發生的事情是,當我點擊按鈕時,視圖變爲空白窗口。我試過硬編碼setCurrentIndex(0),它什麼也不做,setCurrentIndex(1),這是GameScreen應該是什麼,並顯示相同的空白窗口和setCurrentIndex(2),這是超出索引界限,但仍然沒有任何東西。所以連接正在進行,但我不明白爲什麼會出現一個空白窗口而不是GameScreen上的按鈕。
如果有人能向我解釋我錯過了什麼概念以及如何解決它,我將不勝感激。謝謝!
這裏是window.cpp:
Window::Window(QWidget *parent) : QWidget(parent)
{
resize(640, 480);
layout = new QStackedLayout;
createStartScreen();
createGameScreen();
setLayout(layout);
show();
};
void Window::createStartScreen(){
start = new StartScreen();
layout->addWidget(start);
start->setWindow(this);
}
void Window::playGame(){
layout->setCurrentIndex(layout->indexOf(game));
}
void Window::createGameScreen(){
game = new GameScreen();
layout->addWidget(game);
}
startscreen.cpp:
StartScreen::StartScreen(QWidget *parent) : QWidget(parent)
{
newGameButton = new QPushButton("New Game", this);
newGameButton->setGeometry(QRect(QPoint(260, 300), QSize(120,40)));
quitButton = new QPushButton("Quit", this);
quitButton->setGeometry(QRect(QPoint(260, 360), QSize(120,40)));
connect(quitButton, SIGNAL(clicked()), QApplication::instance(), SLOT(quit()));
};
void StartScreen::setWindow(Window *w){
connect(newGameButton, SIGNAL(clicked()), w, SLOT(playGame()));
}
gamescreen.cpp:
GameScreen::GameScreen(QWidget *parent) : QWidget(parent)
{
button = new QPushButton("Hi");
button->setGeometry(QRect(QPoint(260, 260), QSize(120,40)));
};
我在實現您的建議時發現了問題,我沒有將「this」添加到QPushButton中的參數中。我也嘗試使用button - > show(),但它導致按鈕出現在單獨的窗口中。 您對耦合的反饋非常有價值,我會用我的程序改變它。 謝謝你的回答! – DPC