Search code examples
qtqt5qwidgetqtablewidget

Correct way of promoting QTableWidget


I need to have a custom qtablewidget for which I've promoted built in QTableWidget as follows :

Just created a class called Inventory, then inherited it from QTableWidget, added a qtablewidget into mainwindow from the qt designer and promoted it to Inventory class

//inventory.h
#ifndef INVENTORY_H
#define INVENTORY_H    
#include <QTableWidget>

class Inventory : public QTableWidget
{

public:
    Inventory(QTableWidget* parent = 0);
};

#endif // INVENTORY_H


//inventory.cpp
#include "inventory.h"    
Inventory::Inventory(QTableWidget *parent)
    : QTableWidget(parent)
{
    setRowCount(3);
    setColumnCount(3);

    horizontalHeader()->setDefaultSectionSize(160);
    verticalHeader()->setDefaultSectionSize(160);
}

but for some reason it just won't build correctly, throwing this instead:

error: invalid conversion from ‘QWidget*’ to ‘QTableWidget*’ [-fpermissive]
         tableWidget = new Inventory(centralWidget);
                                 ^

in a ui_mainwindow.h file at the line

where tableWidget is declared as Inventory* tableWidget

what is wrong ??

How to fix this ?

p.s.

building with qt 5.7.1 and qtcreator 4.2.0


Solution

  • I think you are confused between your derived class which base is QTableWidget and the constructor for your derived Inventory class. Obviously for Qt and Qt Editor to work, you need to define a Inventory::Inventory(QWidget* parent = 0) constructor, taking a QWidget as a parent widget. ( parent here in the sense of container widget, often a layout) Your constructor is taking a QTableWidget* which seems very fishy to me, and your compiler is telling you that a QWdget* is not a to QTableWidget*, which makes sense.

    Change the signature of the Inventory constructor should make the job