Important: Please read the Qt Code of Conduct -

Subclassing QWidget or QTreeView - which one to choose?

  • I want to make a directory tab.

    If i subclass QWidget and make an object called view in directory.h file:
    QTreeView *view = new QTreeView;
    and add that to a layout in another file where the class i made is Directory *dir_view = new Directory;
    like this: tab_layout->addWidget(dir_view->view);
    Then everything works like it should, I get this nice tree view in my mainwindow

    Now comes the problem, since I have to capture keypressevents when user is focused on QTreeView, then I need to subclass QTreeView instead of QWidget

    I changed my directory class to subclass QTreeView, instead of QWidget and changed all other stuff accordingly, but now tab_layout->addWidget(dir_view); is not displaying any widget.
    when i do after that statement then a window appears and dissapears instantly.

    What could be the cause of this?

  • @Fuchsiaff
    Sub-classing QWidget in itself is not going to get you anywhere. If you need to sub-class, it will be QTreeView you will need to do it on. I think we would need to see what you did for that before understanding how it does not display or appears & disappears.

    BTW, what is your "directory tab"/tab_layout? A QBoxLayout? A QStackedLayout? A QTabWidget? A QStackedWidget ... ?

  • Alright so:

    I have a Tabs class that handles showing directory and adding a new tab to the layout:

    Directory tab is just a QWidget in that code, and that works but the way I need to use it (capture keypressevents when user selects a file in the directory tab and presses a certain key) then i need to make Directory a QTreeView

    I hope this is enough information!

  • Lifetime Qt Champion


    If only key press events en depending on what you want to do with them, an event filter might be enough.

Log in to reply