0

I'm new to QT Creator GUI and I'm having a hard time with Signals and Slots. I'm using QT 4.2.1 to make a word search puzzle for practicing

Below is a portion of my code, creating a 2D puzzle using vectors. I tried to use array but the size of the puzzle will be decided by the user. I had a lot of compile errors using array. So I decided to use Vector

I tried some options from this post: Get index of QPushButton on 2D array QPushButton but they all don't work.

Can you help me to see why the signals and slots are not connected? And is there a way to check if the signal is connected? I would appreciate any helps and feedback. Thank you!

void MainWindow::displayPuzzle(QVector<QVector<QPushButton*>>& button, QVector<QVector<QChar>> puzzle2D){

widget1 = new QWidget;
QGridLayout* l = new QGridLayout;
QSignalMapper mapper;

for (int r = 0; r < puzzle2D.size(); r++) {
    QVector<QPushButton*> vect;
    for (int c = 0; c < puzzle2D[r].size(); c++) {

        //format the button
        vect.push_back(new QPushButton);
        vect.last()->setText(puzzle2D[r][c]);
        vect.last()->setFixedSize(60,60);
        vect.last()->show();
        auto pos = QString{"%1 %2"}.arg(r).arg(c);

        //connect with signals and slots
        mapper.connect(vect.last(), SIGNAL(clicked()), SLOT(map()));
        mapper.setMapping(vect.last(), pos);

        //add button to layout
        l->addWidget(vect.last(), r, c);
        l->setSpacing(0);
        l->setMargin(0);
        l->setContentsMargins(-1,-1,-1,-1);

    }
    button.push_back(vect);
}
connect(&mapper, SIGNAL(mapped(QString)), SLOT(puzzleClick(QString)));

widget1->setLayout(l);

}

void MainWindow::puzzleClick(QString text){

    int r = text.split(" ").at(0).toInt();
    int c = text.split(" ").at(1).toInt();

    QMessageBox::information(this, "click:", r + " " + c );

}
Nina
  • 21
  • 11

1 Answers1

0

The answer you are linking is very complete and useful, I think you should stick with that one. Any suggestion about those methods would be just rewriting the original answer. Maybe you can ask something more specific about what you can't understand of those options.

Another solution, not cited in that answer, would be implementing a class extending QPushButton, intercept the clicked() signal and re-emit it with the data you want. The same thing can be obtained with lambda functions in Qt5 and C++11: have a look at this: qt-custom-qpushbutton-clicked-signal the two answers to this questions explain how to do this.

Community
  • 1
  • 1
valleymanbs
  • 487
  • 3
  • 14
  • I used lambda function, but then realized it's the syntax for Qt 5x. That's why I changed to the current method. I downloaded QT a few years ago, and the version I'm allowed to download for free is 4.2.1. But let me try to update it and use Lambda function. Thank you very much! – Nina Apr 12 '17 at 16:59
  • It works perfectly when I use version 5.8. thank you – Nina Apr 12 '17 at 18:30