Unsolved QObject Problem with using sender() to array of buttons
-
Hello everyone,
I have some problems with programming a qt application. It's a type of game called "Tic Tac Toe".
The main problem is that after clicking any of button the program is not responding. I guess it's about wrong using sender() function.
Here is my code from mainwindow.cpp:#include <QtWidgets> #include <QtGui> #include <QGridLayout> #include <QtCore> #include <QPushButton> #include <QObject> #include <QString> #include "mainwindow.h" #include "ui_mainwindow.h" #define A 3 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { // ui->setupUi(this); Draw(A); } MainWindow::~MainWindow() { delete ui; } MainWindow::Draw(int a) { int count=1; int i, j; QGridLayout *layout = new QGridLayout; QWidget *window = new QWidget; QPushButton *Button[a][a]; for(i=0;i<a;i++) { for(j=0;j<a;j++) { if(count<=(a*a)) { Button[i][j] = new QPushButton(QString::number(count)); Button[i][j]->setMinimumWidth(100); Button[i][j]->setMinimumHeight(100); Button[i][j]->setText(QString::number(count)); Button[i][j]->setProperty("s", i); Button[i][j]->setProperty("d", j); layout->addWidget(Button[i][j],i,j); connect(Button[i][j],SIGNAL(clicked(bool)),this,SLOT(test())); window->setLayout(layout); count++; } } } window->show(); return 0; } void MainWindow::test() { QObject * pSender = sender(); int s = pSender->property("s").toInt(); int d = pSender->property("d").toInt(); if(turn%2==0) { Button[s][d]->setStyleSheet("{ border-image: url(:x.png);}"); Button[s][d]->setEnabled(false); } else { Button[s][d]->setStyleSheet("{ border-image: url(:kolko.jpg);}"); Button[s][d]->setEnabled(false); } turn++; }
my code from header mainwindow.h:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QApplication> #include <QGridLayout> #include <QtGui> #include <QtCore> #include <QtWidgets> namespace Ui { class MainWindow; class ButtonWidget; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: int Draw(int b); void test(); signals: clicked(bool); private: Ui::MainWindow *ui; QPushButton *Button[3][3]; int count=1; int i, j; int turn=0; }; #endif // MAINWINDOW_H
and my main.cpp if u need:
#include "mainwindow.h" #include <QApplication> #include <QGridLayout> #include <QtGui> #include <QtCore> #include <QtWidgets> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; return a.exec(); }
I would really appreciate if you could help me.
-
@MTWK said in QObject Problem with using sender() to array of buttons:
QPushButton *Button[a][a];
You define it twice ...
-
Hi
as mr @Christian-Ehrlicher says
it seems you have both
MainWindow::Draw(int a) {
QPushButton *Button[a][a]; // local to Drawand
private:
Ui::MainWindow *ui;
QPushButton *Button[3][3]; // class member and not the one in Draw