如何为多个QPushButton制作插槽?

时间:2015-07-26 09:39:08

标签: qt

从Qvector设置按钮的数量及其名称(文本)。按下按钮后,我需要重新设置文本并在lineEdit中显示。

标题文件:

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QWidget>
#include <QVector>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = 0);
    ~Dialog();

private slots:   
    void Buttons(QVector<QString>&);

private:
    QVector<QPushButton*>button;
    QString mline;
    QLineEdit *line;
    QVBoxLayout *layout;
    QAction *Clicked;

};

#endif // DIALOG_H

源文件:

#include "dialog.h"

    Dialog::Dialog(QWidget *parent): QDialog(parent)
    {
        this->setFixedSize(this->minimumSize());

        line = new QLineEdit(this);

        layout = new QVBoxLayout(this);

        layout->addWidget(line);

        QVector<QString>v;
        v.append("a");
        v.append("b");
        v.append("c");
        v.append("5");
        v.append("45");
        Buttons(v);

        for(int i=0;i<button.size();i++)
            layout->addWidget(button[i]);

        setLayout(layout);
    }

    Dialog::~Dialog(){}

    void Dialog::Buttons(QVector<QString>&vec)
    {
        if(!button.isEmpty())
            button.clear();

        for(int i=0; i<vec.size();i++)
        {
            button.append(new QPushButton(this));
            button[i]->setText(vec[i]);
            button[i]->show();
        }
    }

对于它我没有使用用户界面(ui),也无法为所有按钮创建插槽。怎么办呢?

2 个答案:

答案 0 :(得分:0)

您可以在您的情况下使用信号/插槽。信号/槽与QObject有关。无论您是否使用QT Designer都无关紧要。在您的代码中,

 for(int i=0; i<vec.size();i++)
 {
     button.append(new QPushButton(this));
     connect(button[i], SIGNAL( clicked() ), this, SLOT(OnButtonClicked()));
     button[i]->setText(vec[i]);
     button[i]->show();
 }

答案 1 :(得分:0)

  1. 您可以使用QButtonGroup来识别按钮并将所有按钮的信号合并到一个插槽中

  2. 实施例

     QButtonGroup  myButtongroup;   
     connect(&myButtonGroup,SIGNAL(buttonClicked(QAbstractButton*),this, SLOT(myButtonClicked (QAbstractButton*)));
      for(int i=0; i<vec.size();i++)
       {   
        QString buttonName = vec[i];
        myButtonGroup.addButton(new QPushButton(buttonName,this),i);
        //Get the button using myButtonGroup.button(i) to add to your layout
        // You can add the buttons to the layout right here to elimate one         more loop
        layout.addWidget(myButtonGroup.button(i));
        }
    
     //Slot for button clicked
     void Dialog::myButtonClicked(QAbstractButton *myButton)
     {
        line->setText(myButton->text());// Adding the button name to line edit 
     }
    
  3. 有关QButtonGroup signals的更多信息,请参阅documentation