您的位置:首页 > 编程语言 > Qt开发

QT控件提升之QPushButton提升为QMenu

2017-03-26 19:05 218 查看
当一个控件进行提升之后, 就有了新的功能, 在原来的一些特性基础上,发生一些新的改变。

QT控件提升方法:

1.需要写一个需要提升为某种功能的类。

2.打开qt设计师, 在对应需要提升的控件, 单击右键, 选择 “提升的窗口部件” , 在提升的类名和头文件输入框里, 分别填上你所写的类, 单击提升铵纽进行提升。



我这边进行了按钮提升为菜单, 部分源码如下:

//
popupbutton.cpp文件


#include "popupbutton.h"

#include <QDebug>

PopupButton::PopupButton(QWidget *parent) :

QPushButton(parent)

{

m_menu = new QMenu(this);

connect(this, SIGNAL(clicked()), this,SLOT(popupMenu()));

}


PopupButton::~PopupButton()

{

}


QMenu *PopupButton::getMenu()

{

return m_menu;

}


void PopupButton::popupMenu()

{

QPoint pos;

int y = pos.y();

pos.setY(y + this->geometry().height());

m_menu->exec(this->mapToGlobal(pos));

}





//
widget.cpp文件


#include "widget.h"

#include "ui_widget.h"

#include <QMenu>

#include <QMessageBox>


Widget::Widget(QWidget *parent) :

QWidget(parent),

ui(new Ui::Widget)

{

ui->setupUi(this);

initMenuButton();

}


Widget::~Widget()

{

delete ui;

}


void Widget::initMenuButton()

{

QMenu* menu = ui->pushButton->getMenu();

QAction *nameAction = new QAction(QLatin1String("Name"), this);

QAction *ageAction = new QAction(QLatin1String("Age"), this);

menu->addAction(nameAction);

menu->addAction(ageAction);


connect(nameAction, SIGNAL(triggered()), this, SLOT(slotNameAction()));

connect(ageAction, SIGNAL(triggered()), this, SLOT(slotAgeAction()));


QMenu* childMenu = menu->addMenu(QLatin1String("child menu"));

QAction *fiveYearOldAction = new QAction(QLatin1String("5"), this);

QAction *tenTearOldAction = new QAction(QLatin1String("10"), this);

childMenu->addAction(fiveYearOldAction);

childMenu->addAction(tenTearOldAction);

}


void Widget::slotNameAction()

{

QMessageBox::information(this, QLatin1String("test"), QLatin1String("You are clicked name action!"));

}


void Widget::slotAgeAction()

{

QMessageBox::information(this, QLatin1String("test"), QLatin1String("You are clicked age action!"));

}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: