Archived:Creating Context Menu from QPushButton
hamishwillee
(Talk | contribs) m (Hamishwillee - Bot update - Move into Archived namespace) |
hamishwillee
(Talk | contribs) m (Text replace - "<code cpp>" to "<code cpp-qt>") |
||
| (2 intermediate revisions by one user not shown) | |||
| Line 26: | Line 26: | ||
== Class Definition == | == Class Definition == | ||
| − | <code cpp> | + | <code cpp-qt> |
#include <QMainWindow> | #include <QMainWindow> | ||
#include "QHBoxLayout" | #include "QHBoxLayout" | ||
| Line 57: | Line 57: | ||
== Class Implementation == | == Class Implementation == | ||
| − | <code cpp> | + | <code cpp-qt> |
#include "button.h" | #include "button.h" | ||
Button::Button(QWidget *parent) : | Button::Button(QWidget *parent) : | ||
| Line 95: | Line 95: | ||
==Related Links== | ==Related Links== | ||
* [[How to use QPushButton (Qt)|How to use QPushButton]] | * [[How to use QPushButton (Qt)|How to use QPushButton]] | ||
| + | <!-- Translation --> [[pt:Archived:Como criar um Menu, usando um QPushButton]] | ||
Latest revision as of 04:14, 11 October 2012
Qt Quick should be used for all UI development on mobile devices. The approach described in this article (based on QWidget) is deprecated.
This article shows how to create a popup menu using a "styled" push button in a QWidget based application. The menu is launched using a QPushButton.
Article Metadata
Code Example
Tested with
Compatibility
Article
Contents |
Class Definition
#include <QMainWindow>
#include "QHBoxLayout"
#include "QPushButton"
namespace Ui {
class Button;
}
class Button : public QMainWindow
{
Q_OBJECT
public:
explicit Button(QWidget *parent = 0);
~Button();
private:
QWidget* win;
QHBoxLayout *lay;
QMenu *menu;
QPushButton* but1;
};
#endif // BUTTON_H
We implement the Push Button in a class called Button, which we derive from QMainWindow. Here we are particularly interested the constructor, so lets discuss below about the constructor in the Class Implementation.
Class Implementation
#include "button.h"
Button::Button(QWidget *parent) :
QMainWindow(parent)
{
win=new QWidget(this);
win->resize(400,500);
lay=new QHBoxLayout(this);
menu=new QMenu(this);
menu->addMenu("Nokia");
menu->addMenu("N96");
menu->addMenu("N97");
but1=new QPushButton("Menu",this);
but1->setMenu(menu);
lay->addWidget(but1);
win->setLayout(lay);
win->setStyleSheet("* { background-color:rgb(125,100,50);color:rgb(200,150,100); padding: 7px}}");
}
Button::~Button()
{
}
In the constructor we create a QWidget (widget) of size 400x500 along with a QHBoxLayout (Layout). We create the QMenu (menu) and add items in the menu. Button have been created using QPushButton and add the button to the widget using addWidget() and then set the widget layout through setLayout() method . setStyleSheet() property holds the widget's style sheet.
Screenshot
Source Code
The full source code presented in this article is available here File:Button.zip


