简体   繁体   中英

C++, add/remove rows from a QTableWidget

I'm creating a simple app with a table and an "Add row" button. Using Qt Creator I thought I can do something like this:

QObject::connect(ui->addRowButton, SIGNAL(clicked()),
                     ui->moneyTableWidget, SLOT(insertRow(1)));

But I can't. I'm really new to Qt and I could be wrong, but think the problem is that insertRow is not a SLOT method for QTableWidget...

How can I achieve the row insertion?

Insert the row in a method of your class. Try this

class TableDialog : public QDialog
{
    Q_OBJECT
public:
    TableDialog(QWidget *parent = 0);
private slots:
    void addRow();
private:
    QTableWidget *tableWidget;
    QDialogButtonBox *buttonBox;
};

And the (partial) implementation:

TableDialog::TableDialog(QWidget *parent) : QDialog(parent) {
tableWidget = new QTableWidget(10, 2);
/* ..... */
connect(addRowButton, SIGNAL(clicked()), this, SLOT(addRow()));

/* ..... */
}

void TableDialog::addRow() {
    int row = tableWidget->rowCount();
    tableWidget->insertRow(row);
/* ..... */
}

The argument to the SLOT() macro is a method signature with argument types only. It can't contain argument names or actual arguments to pass to the slot. That's why you need an additional slot to perform that, as per nc3b's answer. What your code is trying to do is to connect the signal to a slot with one parameter which has the type "1" which is wrong for two reasons: you don't have such slot and "1" isn't a valid type name anyway.

Also, QTableWidget::insertRow() is a slot, as it is listed in the public slots group in the docs. So you can connect a signal to it, but the signal needs to have an int argument in order for the signatures to match.

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