Search code examples
qtqt-designerqtableview

Qt - "Dynamically" promote a Widget


Situation :

For the sake of simplicity, let's assume I have a StackWidget with different tabs, each of which has a widget to manage similar (but not the same) data types.

As the view to display the data and the controls to handle them are mostly the same, I created a new component (ui + cpp + h) named RemoteItemUi that contains the controls and the views and I use this component in each widget, to avoid duplication. It works.

Problem :

Each use case handles different data that each should use a custom TableView class deriving from QTableView. When I use RemoteItemUi, it comes with a QTableView.

I need each instance of RemoteItemUi to use a specialization of QTableView.

NOTES :

  • I know that it is possible to promote widgets to a specialized type, the problem is that if I do this from Qt Designer in RemoteItemUi.ui, it will have the same specialization for all cases.
  • I thought about replacing the QTableView instance dynamically after creation by a custom one, but as Qt doesn't have a clone() method or a copy constructor, I can't do it and retain properties of the original TableView defined in Qt Designer

Solution

  • So, I ended up finding a satisfying solution. The component hasa function to be called by code to replace the TableView.

    Here is the function :

    void RemoteItemUi::initView(QTableView *newView)
    {
        newView->setParent(this);
        newView->setStyleSheet(ui->tableView->styleSheet());
        setTableViewProperties(newView);
    
        auto oldLayoutItem = ui->verticalLayout->replaceWidget(ui->tableView, newView);
        delete oldLayoutItem;
        delete ui->tableView;
        ui->tableView = newView;
    }
    

    It has the following desired properties :

    • Provides a way to set a customized TableView type
    • Keeps the component easily usable in Qt Designer
    • Stylesheets set from Qt Designer are retained in customized TableView

    setTableViewProperties() sets some hardcoded properties to the customized TableView. They can be seen as a hand-made partial copy of properties.