Segolas
Segolas

Reputation: 575

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?

Upvotes: 1

Views: 11796

Answers (2)

Sergei Tachenov
Sergei Tachenov

Reputation: 24919

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.

Upvotes: 1

nc3b
nc3b

Reputation: 16250

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);
/* ..... */
}

Upvotes: 6

Related Questions