Thursday, July 1, 2010

Qt Creator 2.0 exercise: up/down counter - III/3 : Add the code

Add a variable in header

- Click Edit on the left menu, select to edit mainwindow.h

- Add a valiable counterValue under class MainWindow


int counterValue;




Add our Slots:

- Double click on mainwindow.ui, to switch back to Design mode.

- Click the Edit Signals/Slots icon on top bar(or F4)

- Drag a mouse on any empty space on the mainwindow to call out the Configure Connection.


- Click Edit on the right to add new slots.


- Click on the "+" under the Slots box, add new slots, and click OK.
slotClearButtonClicked()
slotUpButtonClicked()
slotDownButtonClicked()


- Click Cancel to finish Configure Connection.

Make connections from signals to slots

- With Edit Signals/Slots enabled, drag from the button Up.


- Select clicked() on the left and slotUpButtonClicked() on the right.


- Repeat to make connection on Down button to slotDownButtonClicked(), Clear button to slotClearButtonClicked().


- Save All, and Rebuild All.

- After Rebuild, in Design mode, with Edit Widgets enabled (F3), right click and button of Up/Down/Clear and select Go to Slot... The code of the slot will be added in mainwindow.cpp, and it will be opened in Edit mode.



Repeat to add the code for all of the four slots(include Quit button).

Add the Code:

- Open mainwindow.cpp in Edit mode

- Scroll down to the new added code for the slots.

- Add the code as:





void MainWindow::on_pushButtonClear_clicked()
{
counterValue = 0;
ui->Counter->setText(QString().setNum(counterValue));
}

void MainWindow::on_pushButtonUp_clicked()
{
counterValue++;
ui->Counter->setText(QString().setNum(counterValue));
}

void MainWindow::on_pushButtonDown_clicked()
{
counterValue--;
ui->Counter->setText(QString().setNum(counterValue));
}

void MainWindow::on_pushButtonQuit_clicked()
{
close();
}

Add the code

- Save All and Build All and Run.

Now we have all the basic function implemented.
Run on emulator