Widget::Widget(QWidget *parent) : QWidget(parent) { button = new QPushButton("OK"); button->setDefault(true); //默認按鈕:當按下enter鍵時,會默認選中[點擊]button button->setParent(this); connect(button, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); } void Widget::slotButtonClicked() { static int i = 0; //局部靜態變量 qDebug() << "slotButtonClicked" << i++; }
通常狀況下,焦點在主窗口上,可是若是咱們須要處理子窗口,須要設置ui
#include "widget.h" #include <QPainter> #include <QDebug> #include <QVBoxLayout> Widget::Widget(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(this); QPushButton *button2, *button3; button = new QPushButton("OK"); layout->addWidget(button); layout->addWidget(button2 = new QPushButton("cancel")); layout->addWidget(button3 = new QPushButton("quit")); button->setDefault(true); //默認按鈕:當按下enter鍵時,會默認選中[點擊]button button2->setDefault(true); //根據上下箭頭切換焦點[V],默認焦點爲第一個設置的setDefault button3->setDefault(true); connect(button, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); connect(button2, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); connect(button3, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); } void Widget::slotButtonClicked() { QPushButton *button = (QPushButton *)sender(); qDebug() << button->text(); }