Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QAction vs QToolButton and when to override the Basic class?

Tags:

qt

I've recently been studying Qt, and have the following questions:

  1. What is the difference between QAction and QToolButton?
  2. How do I know when to override QPushButton? For example, should I override in order to be informed when the mouse enters a QPushButton's bounds? I don't need to in order to get the signal click().
like image 826
Mr.Tu Avatar asked Feb 18 '12 16:02

Mr.Tu


1 Answers

Question 1:

QActions are used to define tasks performed by an application in a way which can be understood by a number of different user interface objects. Using an example from the Qt docs for context:

A QAction is defined; it is given an icon image, a text description, a keyboard shortcut and a longer tooltip description, as well as being linked to a user defined function.

newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new file"));
connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));

Later in the implementation, the QAction is added both to a textual menu bar...

fileMenu->addAction(newAct);

... and an icon-based tool bar:

fileToolBar->addAction(newAct);

The menu bar uses the text description to create an entry in the menu corresponding to the action. Similarly the toolbar uses the icon set on the QAction to create an icon in the toolbar which corresponds to the action. Selecting the menu item, clicking the toolbar icon or pressing the keyboard shortcut will all result in the same effect: that defined by the linking of QAction::triggered() to newFile().

So to directly answer your question: a QAction is an abstract way of defining the various parameters and behaviour of a particular task performed by the application. A QToolbarButton is a UI object (derived from QWidget) created by a QToolbar in response to QToolbar::addAction()


Question 2:

Yes, QPushButton has a clicked() signal inherited from QAbstractButton, but it does indeed lack a way to inform when the mouse has entered its bounds. You have a couple of options in order achieve this, but first you need to first set the mouseTracking property to be enabled. This will allow you to receive mouse move events on the QPushButton even if no mouse buttons are pressed. With that done you need to explore one of the following options:

  1. As you suggest, you could subclass QPushButton and reimplement mousePressEvent in order to respond to the mouse position.
  2. You could install another widget as an eventFilter on the QPushButton, and watch for events of type (QEvent::MouseMove).
like image 104
sam-w Avatar answered Oct 26 '22 23:10

sam-w