PDA

View Full Version : My class isnt working properly and i dont know why (Newbie)



22eragon22
20th April 2020, 22:04
Hi!
Im new to Qt and im trying to make a class, that will create a board of buttons, depending on a user's choice but it doesnt work properly and i dont know why...

here is my code

rysuj_plansze.h




#ifndef RYSUJ_PLANSZE_H
#define RYSUJ_PLANSZE_H

#include <QPushButton>
#include <QGridLayout>


class rysuj_plansze
{
public:
void rysuj();
private:
QPushButton *button;
};




rysuj_plansze.cpp




#include "rysuj_plansze.h"
#include <QApplication>
#include <QLabel>
#include <QtWidgets>
#include <QtCore>
#include <QMessageBox>
#include <QDialog>

void rysuj_plansze::rysuj()
{

QWidget *window = new QWidget;
QGridLayout *layout = new QGridLayout;
window->setWindowTitle("TIc-Tac-Toe");



QMessageBox msgBox;
msgBox.addButton("3na3", QMessageBox::YesRole);
msgBox.addButton("5na5", QMessageBox::NoRole);
msgBox.setIcon(QMessageBox::Question);
msgBox.setText("Which board do you chose?");
msgBox.exec();




if(msgBox.exec() == QMessageBox::Yes)
{
int width = 3;
int height = 3;

for(int i = 0; i<height; i++)
{
for(int j = 0; j<width; j++)
{
QPushButton *button = new QPushButton;
layout->addWidget(button,i,j);
}
}
}



else if(msgBox.exec() == QMessageBox::No)
{
int width = 20;
int height = 20;

for(int i = 0; i<height; i++)
{
for(int j = 0; j<width; j++)
{
QPushButton *button = new QPushButton;
layout->addWidget(button,i,j);
}
}
}



window->setLayout(layout);
window->show();
}





main.cpp




#include "rysuj_plansze.h"
#include <QApplication>
#include <QLabel>
#include <QtWidgets>
#include <QtCore>
#include <QDialog>

int main(int argc, char *argv[])
{
QApplication app(argc, argv);


rysuj_plansze R;
R.rysuj();


return app.exec();
}






When i try to run it in main.cpp the messagebox is displayed multiple times (instead of being displayed once) and in the end the window with the board is empty(instead of being 3on3 or 20on20)

Ginsengelf
21st April 2020, 06:50
Hi, you call QMessageBox::exec() multiple times:
line 23: msgBox.exec();
line 28: if(msgBox.exec() == QMessageBox::Yes)
line 45: else if(msgBox.exec() == QMessageBox::No)
Each time the messagebox is shown. Call exec() only once and store the return value for use in the if() and else if() lines, or use switch-case.

Ginsengelf

22eragon22
21st April 2020, 07:50
Thank You! its working rn!!!