简体   繁体   中英

qt how to connect 2D array of QPushButton and return the location

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 );

}

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.

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