简体   繁体   中英

making single function for array of pushbuttons in QT

I'm new in QT. I have 35 push_buttons in an array. I want to write single function for this array of buttons. that function will only set string, different for each button. like "10,10" nextone like "15,15" etc. I have seen signalmappers which i can able to understand.

give simple and easy idea.

for (int i = 0; i < 35;i++){
    PB << new QPushButton();
}

ui->setupUi(this);

PB[0]=ui->pB_00;PB[1]=ui->pB_01;PB[2]=ui->pB_02;PB[3]=ui->pB_03;
PB[4]=ui->pB_04;PB[5]=ui->pB_05;PB[6]=ui->pB_06;PB[7]=ui->pB_07;
PB[8]=ui->pB_08;PB[9]=ui->pB_09;PB[10]=ui->pB_10;PB[11]=ui->pB_11;
PB[12]=ui->pB_12;PB[13]=ui->pB_13;PB[14]=ui->pB_14;PB[15]=ui->pB_15;
PB[16]=ui->pB_16;PB[17]=ui->pB_17;PB[18]=ui->pB_18;PB[19]=ui->pB_19;
PB[20]=ui->pB_20;PB[21]=ui->pB_21;PB[22]=ui->pB_22;PB[23]=ui->pB_23;
PB[24]=ui->pB_24;PB[25]=ui->pB_25;PB[26]=ui->pB_26;PB[27]=ui->pB_27;
PB[28]=ui->pB_28;PB[29]=ui->pB_29;PB[30]=ui->pB_30;PB[31]=ui->pB_31;
PB[32]=ui->pB_32;PB[33]=ui->pB_33;PB[34]=ui->pB_34;

You could add a function that only takes two parameters. The first parameter would be which button to access. The next one would be the text to set. Example:

void Parent::changeText(int button, QString text)
{
    PB[button].setText(text);
}

You can cycle through to do multiple buttons.

If the buttons already exist in your ui element, your current loop does not need to create new QPushButtons. Instead of using designer to insert your buttons you can do it in code.

// Your button array, this is likely a private member in your class.
QList< QPushButton* > PB;

for( auto i = 0; i < 35; ++i )
{
    // Create new button with textValue == "i" 
    auto button = new QPushButton{ QString::number( i ) };

    // Store in your list
    PB << button;

    // Add to ui
    ui->containerQWidget->layout()->addWidget( button );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM