翻譯|使用教程|編輯:鮑佳佳|2020-08-21 12:04:47.623|閱讀 152 次
概述:創(chuàng)建自定義插槽和信號非常簡單。插槽就像普通方法一樣,但是周圍的裝飾很小,而所以幾乎不需要或根本不需要實現(xiàn)。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
Qt(發(fā)音為“ cute”,而不是“ cu-tee”)是一個跨平臺框架,通常用作圖形工具包,它不僅創(chuàng)建CLI應用程序中也非常有用。而且它也可以在三種主要的臺式機操作系統(tǒng)以及移動操作系統(tǒng)(如Symbian,Nokia Belle,Meego Harmattan,MeeGo或BB10)以及嵌入式設備,Android(Necessitas)和iOS的端口上運行。更多Qt產(chǎn)品詳情點擊這里>>
創(chuàng)建自定義插槽和信號非常簡單。插槽就像普通方法一樣,但是周圍的裝飾很小,而所以幾乎不需要或根本不需要實現(xiàn)。
下面對此進行了描述:
為了實現(xiàn)一個插槽,我們首先需要使該類能夠發(fā)送信號并具有插槽(請參閱上一章)。這是通過在類聲明中設置Q_OBJECT宏(通常在標頭中)來完成的。之后,應在相應的部分中聲明一個插槽,并將其作為常規(guī)方法實現(xiàn)。最后,插槽連接到信號。
創(chuàng)建信號至于插槽,我們首先需要添加Q_OBJECT宏。信號也應該在信號部分聲明,并且不需要實現(xiàn)它們。
Windows
#ifndef WINDOW_H #define WINDOW_H #includeclass QPushButton; class Window : public QWidget { public: explicit Window(QWidget *parent = 0); private: QPushButton *m_button; }; #endif // WINDOW_H
window.cpp
#include "window.h" #includeWindow::Window(QWidget *parent) : QWidget(parent) { // Set size of the window setFixedSize(100, 50); // Create and position the button m_button = new QPushButton("Hello World", this); m_button->setGeometry(10, 10, 80, 30); }
我們可能想要刪除先前的連接,該連接在單擊該按鈕時會退出應用程序。現(xiàn)在,我們希望在單擊按鈕時更改文本。更準確地說,我們希望按鈕可以被選中,并且當選中時,它顯示為“已選中”,而當未選中時,它將恢復為“ Hello World”。
QPushButton沒有實現(xiàn)這種特定的插槽,因此我們必須自己實現(xiàn)。如前所述,我們必須添加Q_OBJECT宏。
class Window : public QWidget { Q_OBJECT public: explicit Window(QWidget *parent = 0); private: QPushButton *m_button; };
我們還添加了自定義插槽。
void QPushButton::clicked(bool checked)
我們可以實現(xiàn)一個具有以下簽名的插槽:
void Window::slotButtonClicked(bool checked);
在大多數(shù)情況下,按照慣例,我們會在專用和受保護的插槽前加上“插槽”作為前綴。在這里,我們不希望將此插槽公開為公共功能,可以將其設為私有。
Windows.h
#ifndef WINDOW_H #define WINDOW_H #includeclass QPushButton; class Window : public QWidget { Q_OBJECT public: explicit Window(QWidget *parent = 0); private slots: void slotButtonClicked(bool checked); private: QPushButton *m_button; }; #endif // WINDOW_H
該插槽的實現(xiàn)是
void Window::slotButtonClicked(bool checked) { if (checked) { m_button->setText("Checked"); } else { m_button->setText("Hello World"); } }
我們需要使按鈕可檢查,并建立連接,我們必須在構造函數(shù)中添加以下代碼:
m_button->setCheckable(true); connect(m_button, SIGNAL (clicked(bool)), this, SLOT (slotButtonClicked(bool)));
結果代碼如下:
window.cpp
#include "window.h" #includeQtitanRibbon、QtitanChart、QtitanNavigation、QtitanDocking、QtitanDataGrid在線訂購現(xiàn)直降1000元,歡迎咨詢慧都獲取更多優(yōu)惠>>Window::Window(QWidget *parent) : QWidget(parent) { // Set size of the window setFixedSize(100, 50); // Create and position the button m_button = new QPushButton("Hello World", this); m_button->setGeometry(10, 10, 80, 30); m_button->setCheckable(true); connect(m_button, SIGNAL (clicked(bool)), this, SLOT (slotButtonClicked(bool))); } void Window::slotButtonClicked(bool checked) { if (checked) { m_button->setText("Checked"); } else { m_button->setText("Hello World"); } }
本站文章除注明轉載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自: