QT按鍵增加按鍵音代碼功能,代碼如下:
void QKeyPushButton::mouseReleaseEvent(QMouseEvent *event)
{
QPushButton::mouseReleaseEvent(event);
mplay->execute(program,arguments); //此處調用"aplay click.wav"播放按鍵音文件
}
但是這樣會導致一個現象,即在按鍵過快按下的時候,按鍵音延遲響應,給人一種“卡”的感覺,在此採用了單例模式的設計方法解決了該問題。關鍵代碼如下:
{
Q_OBJECT
public:
static QKeythread* GetInstance();
public slots:
void play_key_sound(void);
void play_sound_slot(void);
private:
QKeythread();
static QKeythread *m_keyDeal;
QProcess *mplay;
QString program;
QStringList arguments;
};
QKeythread::QKeythread() //單例類構造函數
{
mplay = new QProcess(this);
program = "aplay";
arguments<<SOUND_PATH;
}
QKeythread *QKeythread::GetInstance() //單例類靜態實現方法
{
if(m_keyDeal == NULL)
{
m_keyDeal = new QKeythread;
}
return m_keyDeal;
}
void QKeythread::play_sound_slot() //播放按鍵音樂的槽函數
{
mplay->start(program,arguments);
}
然後在按鍵類的構造函數裏將播放音樂的信號和槽聯繫起來即可:
QKeyPushButton::QKeyPushButton(QWidget *parent)
: QPushButton(parent)
{
this->setStyleSheet(QString(DEFAULT_STYLE_BUTTON) + QString(DEFAULT_BACKGROUND_BUTTON));
connect(this,SIGNAL(play_key_sound()),QKeythread::GetInstance(),SLOT(play_sound_slot()));
}
採用這種方法的原理可以概括如下:按鍵過快時,按鍵事件仍全部響應,而按鍵音播放事件則有選擇的響應。