c++qtqt-signalsslotqsignalmapper

Updating mapping when using QSignalMapper


I have created a QPushButton in the last column of tableview (which contains ip address of the connected clients to my application). With that button I am able to disconnect the connected client in that particular row using button release signal and slot 'handlebutton(int)'.

The code is -

MainWindow::MainWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QSortFilterProxyModel *model = new QSortFilterProxyModel(this);
    model = pCApp->guiClient()->getConnectionManagement()->getProxyModel();
    ui->tableView->setModel(model);
    QPushButton *button;
    QSignalMapper *mapper = new QSignalMapper(this);
    QObject::connect(mapper, SIGNAL (mapped(int)), this, SLOT (handleButton(int)));
    for (int i = 0; i < model->rowCount(); i++)
    {
        button = new QPushButton;
        button->setText("Disconnect " + QString::number(i));
        button->setStyleSheet("QPushButton { color: #E5E5E5; }");
        ui->tableView->setIndexWidget(model->index(i,2, QModelIndex()), button);
        QObject::connect(button, SIGNAL(released()), mapper, SLOT(map()));
        mapper->setMapping(button, i);
    }
    setAttribute(Qt::WA_DeleteOnClose);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleButton(int row)
{
    CGuiClientMessage message;
    message.setRecipient(CGuiMessage::R_GUISERVER);
    message.setObjectId(0);
    message.setCommand(CGuiMessage::DISCONNECT_PEER);
    message.Parameter().setAttribute("Peers", ui->tableView->model()->data(ui->tableView->model()->index(row,1)).toString());
    pCApp->guiClient()->SendMessageToPts(message);
}

Now, I want to update mapping. Where shall I do that in the slot or somewhere else? Please, if anyone can suggest me how and where to do it?

Thanks in advance!


Solution

  • If I got it right, you just want to unmap a button as soon as it was clicked and corresponding client was disconnected. Then you can just call mapper->removeMapping(button) on the appropriate button. If you need to map this button again - call mapper->setMapping(button, i) again.

    Keep in mind, it does not disconnect button released signal from the mapper. If you need - use QObject::disconnect explicitely.

    Also if your button gets destroyed - both removeMapping and disconnect are done for you so you don't have to worry about that.