Qt QTableWidget 点击事件 重复问题的解决

         在做一个Qt项目时遇到一个小问题,再晚上也没搜到。情况是这样的,我初始化完一个table后,点击里面的一行会产生一个事件,这次提醒了一次,在table中删除了一行刷新这个table后,点击一行产生点击事件2次,再刷新一次table,产生点击事件3次,没刷新一次点击事件多重复1次,很是郁闷。

         经过分析,最后发现是connect函数的问题,解决办法是:在每次刷新列表前解绑之前绑定的事件,这样就不会重复产生点击事件了。代码如下:

void MainWindow::initUserList()
{
    disconnect(ui->tableWidgetUser,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(onUserClickListener(QModelIndex)));
    disconnect(ui->tableWidgetUser,SIGNAL(itemPressed(QTableWidgetItem*)),this,SLOT(slotItemClicked(QTableWidgetItem*)));
    userList = util->getUserList();
    ui->tableWidgetUser->clear();
    ui->tableWidgetUser->clearContents();
    QStringList headList;
    headList.push_back("用户id");
    headList.push_back("用户名字");
    headList.push_back("用户寻列号");
    ui->tableWidgetUser->setRowCount(userList.size());
    ui->tableWidgetUser->setColumnCount(headList.size());
    ui->tableWidgetUser->setHorizontalHeaderLabels(headList);//  设置表头
    ui->tableWidgetUser->horizontalHeader()->setVisible(true);
    /*设置表格为整行选中*/
    ui->tableWidgetUser->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidgetUser->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidgetUser->horizontalHeader()->resizeSections(QHeaderView::Stretch);

    for (int i = 0; i < userList.size(); ++i)
    {
        User user = userList.at(i);
        ui->tableWidgetUser->setItem(i,0,new QTableWidgetItem(user.getUserId()));
        ui->tableWidgetUser->setItem(i,1,new QTableWidgetItem(user.getUserName()));
        ui->tableWidgetUser->setItem(i,2,new QTableWidgetItem(user.getUserLicense()));
    }
    connect(ui->tableWidgetUser,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(onUserClickListener(QModelIndex)));
    connect(ui->tableWidgetUser,SIGNAL(itemPressed(QTableWidgetItem*)),this,SLOT(slotItemClicked(QTableWidgetItem*)));
}


你可能感兴趣的:(C++)