excalibur1491
excalibur1491

Reputation: 1221

Design issue: apply specific treatment to a subclass only manipulating the superclass

I am working in a project where I have a design issue that I don't know how to solve. I would like to find the best solution for extensibility of the code. The project consists in a web browser with tabs, but in the tabs there are not only webpages, I can have other kinds of widgets. I am using Qt, and so the widget in the tabs are QWidgets (QWebview and other types that I still have to code myself). Anyway, I'm going to try to keep this question generic enough.

There is a class QWidget from which 2 classes inherit: QWebView and MyWidget. I have a container (QTabWidget) that can contain both of them, since it can contain QWidgets. Moreover, I have a button (the previous page button, for instance), that only applies to one kind of QWidget: QWebView. So, when I press this button, I ask the QTabWidget for the current QWidget and if its a QWebView I do something, otherwise I don't do anything. That is the problem: I need to be able to distinguish between the two different types: if I ask the QTabWidget to give me the currentWidget, it gives me a QWidget*, but I don't know whether its a QWwbView or a MyWidget and so I have to doa nasty dynamic_cast<> to check the real type. This means that if I add a new MyWidget2 with another action, I will have to update all my code where there are dynamic_cast<>, and I don't want that.

I have been thinking of command pattern and startegy pattern but I don't think they applu realy well.

Do you have any advise? Thanks

Upvotes: 1

Views: 56

Answers (1)

Stuart Golodetz
Stuart Golodetz

Reputation: 20646

At an abstract level, it sounds like you need some way of mapping the various widget types to the actions (e.g. "go to previous page") that they can support - that way, when you add a new widget type, you specify its actions as well. Depending on the currently-viewed tab, you can then enable/disable the relevant actions, so that when the user is able to perform an action you know that it will work for the type of tab currently being viewed.

One way of doing this would be to add a virtual member function to your base widget type that returns the relevant actions. You then cast the QWidgets returned by the tab widget to your base widget type. This still involves a cast (because QTabWidget isn't geared up to return widgets of your base widget type), but it gets rid of the maintainability problem when you add new types of widget.

Upvotes: 1

Related Questions