在工具栏中嵌入其他控件

在工具栏中嵌入其他控件

如何在工具栏中嵌入其他控件?

1、新建toolbar.h

#ifndef TOOLBAR_H
#define TOOLBAR_H
#include <QtGui>

class ToolBar : public QMainWindow
{
    Q_OBJECT

public:
    ToolBar();

public slots:
    void slotComboBox(QString);
    void slotSpinBox(QString);

private:
    QTextEdit *textEdit;
    QComboBox *comboBox;
    QSpinBox *spinBox;
};

#endif // TOOLBAR_H

2、创建toolbar.cpp

#include "toolbar.h"

ToolBar::ToolBar():QMainWindow()
{
    setWindowTitle(tr("myToolBar"));

    textEdit = new QTextEdit(this);
    textEdit->setReadOnly(true);
    setCentralWidget(textEdit);

    QToolBar *toolBar = addToolBar("control");
    QLabel *label1 = new QLabel(tr("ctrl1: "));
    comboBox = new QComboBox;
    comboBox->insertItem(0,tr("ComboBox 0"));
    comboBox->insertItem(1,tr("ComboBox 1"));
    comboBox->insertItem(2,tr("ComboBox 2"));
    toolBar->addWidget(label1);
    toolBar->addWidget(comboBox);
    toolBar->addSeparator();
    QLabel *label2 = new QLabel(tr("ctrl2: "));
    spinBox = new QSpinBox;
    spinBox->setRange(1,10);
    toolBar->addWidget(label2);
    toolBar->addWidget(spinBox);

    connect(comboBox,SIGNAL(currentIndexChanged(QString)),this,SLOT(slotComboBox(QString)));
    connect(spinBox,SIGNAL(valueChanged(QString)),this,SLOT(slotSpinBox(QString)));
}

void ToolBar::slotComboBox(QString combo)
{
    QString doc;
    QString spinStr;
    doc = "QComboBox: " + combo + "\n"
            + "QSpinBox: " + spinStr.setNum(spinBox->value());
    textEdit->setText(doc);
}

void ToolBar::slotSpinBox(QString value)
{
    QString doc;
    doc = "QComboBox: " + comboBox->currentText() + "\n"
            + "QSpinBox: " + value;
    textEdit->setText(doc);
}

3、创建main.cpp

#include <QApplication>

#include "toolbar.h"

int main(int argc,char *argv[])
{
    QApplication app(argc, argv);

    ToolBar *toolbar = new ToolBar;
    toolbar->show();

    return app.exec();
}

4、运行
在工具栏中嵌入其他控件_第1张图片

5、资源代码

你可能感兴趣的:(工具栏,控件)