自定义菜单栏
Posted Respect@
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义菜单栏相关的知识,希望对你有一定的参考价值。
自定义菜单栏
自定义菜单栏
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myaction.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
MyAction *action = new MyAction;
QMenu* menu = ui->menuBar->addMenu("编辑(&E)");
menu->addAction(action);
connect(action,&MyAction::getText,this,&MainWindow::setText);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setText(const QString &str)
{
ui->textEdit->setText(str);
}
#include "myaction.h"
#include <QSplitter>
#include <QLabel>
MyAction::MyAction(QObject* parent):QWidgetAction(parent)
{
lineEdit = new QLineEdit;
connect(lineEdit,&QLineEdit::returnPressed,
this,&MyAction::sendText);
}
QWidget *MyAction::createWidget(QWidget *parent)
{
//判断父部件是否继承自菜单或者工具栏
//如果是则创建父部件的子部件并放回子部件
if(parent->inherits("QMenu") || parent->inherits("QToolBar")){
QSplitter *splitter = new QSplitter(parent);
QLabel *label = new QLabel("插入文本:");
splitter->addWidget(label);
splitter->addWidget(lineEdit);
return splitter;
}
return 0;
}
void MyAction::sendText()
{
emit getText(lineEdit->text());
lineEdit->clear();
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void setText(const QString& str);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
myaction.h
#ifndef MYACTION_H
#define MYACTION_H
#include <QWidgetAction>
#include <QLineEdit>
class MyAction : public QWidgetAction
{
Q_OBJECT
public:
MyAction(QObject* parent = 0);
protected:
QWidget* createWidget(QWidget *parent);
signals:
void getText(const QString& string);
private slots:
void sendText();
private:
QLineEdit* lineEdit;
};
#endif // MYACTION_H
以上是关于自定义菜单栏的主要内容,如果未能解决你的问题,请参考以下文章