Qt4 SegmentationFault on QTableWidget::setItem

Qt4 SegmentationFault on QTableWidget::setItem

本文关键字:setItem QTableWidget on SegmentationFault Qt4      更新时间:2023-10-16

我这里有一个非常奇怪的问题。我的程序是SegmentationFault,当我在表中设置项目时。这是我的代码。

头:

class Program : public QMainWindow {
    Q_OBJECT
    public:
        Program();
    private:
        QTableWidget *table;
    private slots:
        void newSlot();
}

Cpp文件:

Program::Program() : QMainWindow() {
    ....
    ....
    ....
    ....
    table = new QTableWidget();
    table->setRowCount( 0 );
    table->setColumnCount( 2 );
    ....
    ....
    ....
}
void Program::newSlot() {
    ....
    ....
    ....
    table->insertRow( table->rowCount() );
    table->setItem( table->rowCount() - 1, 0, new QTableWidgetItem( "something" ) );
    table->setItem( table->rowCount() - 1, 1, new QTableWidgetItem( "something" ) );
    ....
    ....
    ....
}

问题是当程序在newSlot()中达到table->setItem( ... )时,我得到了分割故障。我是不是在什么地方犯了愚蠢的错误,导致了这一团糟?因为我在其他地方使用了完全相同的代码,没有任何问题。

必须指定列数:

table->setColumnCount( 2 );

table->setItem( table->rowCount() - 1, 0, new QTableWidgetItem( "something" ) );
...