当前位置:网站首页>Acceptance and neglect of events
Acceptance and neglect of events
2022-07-27 05:02:00 【PHP code】
In the last chapter, we introduced the relevant contents of the event . We have mentioned , Events can be accepted and ignored according to the situation . Now? , Let's learn more about events .
Let's start with a piece of code :
//!!! Qt5
// ---------- custombutton.h ---------- //
class CustomButton : public QPushButton
{
Q_OBJECT
public:
CustomButton(QWidget *parent = 0);
private:
void onButtonCliecked();
};
// ---------- custombutton.cpp ---------- //
CustomButton::CustomButton(QWidget *parent) :
QPushButton(parent)
{
connect(this, &CustomButton::clicked,
this, &CustomButton::onButtonCliecked);
}
void CustomButton::onButtonCliecked()
{
qDebug() << "You clicked this!";
}
// ---------- main.cpp ---------- //
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CustomButton btn;
btn.setText("This is a Button!");
btn.show();
return a.exec();
}
This is a simple piece of code , After our previous period of study , We can already know the running result of this code : Click button , It will print out “You clicked this!” character string . This is what we introduced earlier . below , We ask CustomButton Class to add an event function :
// CustomButton
...
protected:
void mousePressEvent(QMouseEvent *event);
...
// ---------- custombutton.cpp ---------- //
...
void CustomButton::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
qDebug() << "left";
} else {
QPushButton::mousePressEvent(event);
}
}
...
We rewrote CustomButton Of mousePressEvent() function , That is, press the mouse . In this function , We judged that if the mouse pressed the left button , Then print it out “left” character string , otherwise , Call the function with the same name of the parent class . Compile and run this code , When we click the button ,“You clicked this!” The string no longer appears , only one “left”. in other words , We override the implementation of the parent class . From this we can see that , Parent class QPushButton Of mousePressEvent() The function must emit clicked() The signal , Otherwise , How can our slot function not be executed ? This implies a very important detail :** When overriding the event callback function , Always pay attention to whether you need to call the function with the same name of the parent class to ensure that the original implementation can still be carried out !** Like our CustomButton 了 , If we cover functions like this ,clicked() The signal will never happen , The slot function you connect to this signal will never be executed . This mistake is very hidden , It will probably waste you a lot of time to find . Because there will be no prompt for this error . To some extent , Our components “ Ignore ” The event of the parent class , But this is more of an act against one's will , A mistake .
By calling the function with the same name of the parent class , We can Qt The transmission of events is seen as a chain : If the subclass does not handle this event , Will continue to pass to its parent class .Qt The event object of has two functions :accept() and ignore(). Just like their names , The former is used to tell Qt, The event handler of this class wants to handle this event ; The latter tells Qt, The event handler of this class doesn't want to handle this event . In the event handler , have access to isAccepted() To check whether this event has been received . say concretely : If an event handler function calls the of an event object accept() function , This event will not be spread to it Parent component ; If it invokes the ignore() function ,Qt Will find another recipient from its parent component .
in fact , We rarely use accept() and ignore() function , But like the example above , If you want to ignore Events ( The so-called neglect , It means that you don't want this event ), Just call the response function of the parent class . Remember we said ,Qt The events in are protected Of , therefore , The overridden function must have a response function in its parent class , therefore , This method is feasible . Why do you do this , Instead of calling these two functions manually ? Because we cannot confirm whether the handler in the parent class has additional operations . If we ignore events directly in subclasses ,Qt Will look for other recipients , The operation of the parent class of this subclass will be ignored ( Because the function with the same name of the parent class is not called ), This can be potentially dangerous . In order to avoid calling accept() and ignore() function , Instead, try to call the parent class implementation ,Qt Made a special design : The event object defaults to accept Of , As the parent of all components QWidget The default implementation of is to call ignore(). In this way , If you implement the event handler yourself , Do not call QWidget Default implementation of , You're accepting the event ; If you want to ignore Events , Just call QWidget Default implementation of . We have already explained this point . This can be understood from the code level below , We can check it out QWidget Of mousePressEvent() Implementation of function :
//!!! Qt5
void QWidget::mousePressEvent(QMouseEvent *event)
{
event->ignore();
if ((windowType() == Qt::Popup)) {
event->accept();
QWidget* w;
while ((w = QApplication::activePopupWidget()) && w != this){
w->close();
if (QApplication::activePopupWidget() == w)
w->hide(); // hide at least
}
if (!rect().contains(event->pos())){
close();
}
}
}
This code is in Qt4 and Qt5 Basically the same in ( The difference lies in activePopupWidget() a line ,Qt4 The version is qApp->activePopupWidget()). Notice the first statement of the function :event->ignore(), If no subclass overrides this function ,Qt This event will be ignored by default , Continue to find the next event recipient . If we're in subclass mousePressEvent() Function directly calls accept() perhaps ignore(), Without calling the function with the same name of the parent class ,QWidget::mousePressEvent() Function about Popup The judgment code will not be executed , Therefore, there may be a strange phenomenon of default .
in the light of accept() and ignore(), Let's take another example :
class CustomButton : public QPushButton
{
Q_OBJECT
public:
CustomButton::CustomButton(QWidget *parent)
: QPushButton(parent)
{
}
protected:
void mousePressEvent(QMouseEvent *event)
{
qDebug() << "CustomButton";
}
};
class CustomButtonEx : public CustomButton
{
Q_OBJECT
public:
CustomButtonEx::CustomButtonEx(QWidget *parent)
: CustomButton(parent)
{
}
protected:
void mousePressEvent(QMouseEvent *event)
{
qDebug() << "CustomButtonEx";
}
};
class CustomWidget : public QWidget
{
Q_OBJECT
public:
CustomWidget::CustomWidget(QWidget *parent)
: QWidget(parent)
{
}
protected:
void mousePressEvent(QMouseEvent *event)
{
qDebug() << "CustomWidget";
}
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow::MainWindow(QWidget *parent = 0)
: QMainWindow(parent)
{
CustomWidget *widget = new CustomWidget(this);
CustomButton *cbex = new CustomButton(widget);
cbex->setText(tr("CustomButton"));
CustomButtonEx *cb = new CustomButtonEx(widget);
cb->setText(tr("CustomButtonEx"));
QVBoxLayout *widgetLayout = new QVBoxLayout(widget);
widgetLayout->addWidget(cbex);
widgetLayout->addWidget(cb);
this->setCentralWidget(widget);
}
protected:
void mousePressEvent(QMouseEvent *event)
{
qDebug() << "MainWindow";
}
};
This code is in a MainWindow Added a CustomWidget, There are two button objects :CustomButton and CustomButtonEx. Each class overrides mousePressEvent() function . Run the program and click CustomButtonEx, The result is
CustomButtonEx
This is because we have rewritten the mouse press event , But it doesn't call the parent function or explicitly set accept() or ignore(). And now we have CustomButtonEx Of mousePressEvent() Add a sentence to the first line event->accept(), Rerun , It turns out that the results are the same . As we said before ,QEvent The default is accept Of , There is no difference in calling this function . Then we will CustomButtonEx Of event->accept() Change to event->ignore(). The result of this run is
CustomButtonEx
CustomWidget
ignore() It shows that we want the event to continue to spread , therefore CustomButtonEx The parent component of CustomWidget Also received this event , So I output my own results . Empathy ,CustomWidget It doesn't call the parent function or explicitly set accept() or ignore(), So the spread of the incident stopped . Here's what's interesting ,CustomButtonEx The event of is propagated to the parent component CustomWidget, Not its parent CustomButton. Event propagation is at the component level , Instead of relying on class inheritance .
Next we continue to test , stay CustomWidget Of mousePressEvent() add QWidget::mousePressEvent(event). The output this time is
CustomButtonEx
CustomWidget
MainWindow
If you put QWidget::mousePressEvent(event) Change to event->ignore(), It turns out the same thing . As we said before ,QWidget The default is to call event->ignore().
In a special case , We have to use accept() and ignore() function , That is the event of window closing . For window closing QCloseEvent event , call accept() signify Qt Will stop the propagation of the event , The window closed ; call ignore() It means that the event continues to spread , That is, prevent the window from closing . Back to the simple text editor we wrote earlier . We add the following code to the constructor :
//!!! Qt5
...
textEdit = new QTextEdit(this);
setCentralWidget(textEdit);
connect(textEdit, &QTextEdit::textChanged, [=]() {
this->setWindowModified(true);
});
setWindowTitle("TextPad [*]");
...
void MainWindow::closeEvent(QCloseEvent *event)
{
if (isWindowModified()) {
bool exit = QMessageBox::question(this,
tr("Quit"),
tr("Are you sure to quit this application?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) == QMessageBox::Yes;
if (exit) {
event->accept();
} else {
event->ignore();
}
} else {
event->accept();
}
}
setWindowTitle() Function can be used [] This grammar indicates , When the content of the window changes ( adopt setWindowModified(true) Function notification ),Qt It will be automatically above the title [] Replace the position with * Number . We use Lambda Expression connection QTextEdit::textChanged() The signal , take windowModified Set to true. Then we need to rewrite closeEvent() function . In this function , Let's first judge whether it has been modified , If there is , Then a query box pops up , Ask if you want to quit . If the user clicks “Yes”, Then accept the closing event , The operation of this event is to close the window . therefore , Once you accept the event , The window will be closed ; Otherwise, the window will remain . Of course , If the contents of the window have not been modified , Then directly accept the event , close window .
边栏推荐
- 对话框简介
- HCIA dynamic routing OSPF experiment
- Interesting C language
- Introduction to MySQL optimization
- C language - two dimensional array, pointer
- ps太卡怎么办?几步帮您解决问题
- How do I reset Photoshop preferences? PS method of resetting preferences
- 老子云携手福昕鲲鹏,首次实现3D OFD三维版式文档的重大突破
- Replication of df-gan experiment -- detailed steps of replication of dfgan and forwarding from remote port to local port using mobaxtem
- Counting Nodes in a Binary Search Tree
猜你喜欢
随机推荐
Hiding skills of Photoshop clipping tool
Hiding skills of Photoshop clipping tool
Plato farm is expected to further expand its ecosystem through elephant swap
Complete Binary Tree
[search] - multi source BFS + minimum step model
HCIA dynamic routing rip basic experiment
使用mq消息队列来进行下单流程的高并发设计,消息挤压,消息丢失,消息重复的产生场景和解决方案
【报错】:Cannot read properties of undefined (reading ‘prototype‘)
【C语言】动态内存管理
【搜索】双向广搜 + A*
Unit test Chapter6
Error: cannot read properties of undefined (reading 'then')
Cache read / write policies: cacheside, read/writethrough and writeback policies
CDH cluster integration external Flink (improved version - keep pace with the times)
Reproduce ssa-gan using the nine day deep learning platform
2022 T2i text generated image Chinese Journal Paper quick view-1 (ecagan: text generated image method based on channel attention mechanism +cae-gan: text generated image technology based on transforme
Affine transformation module and conditional batch Standardization (CBN) of detailed text generated images
What about PS too laggy? A few steps to help you solve the problem
事件(event)
标准对话框 QMessageBox








![[search] two way search + A*](/img/b1/115f75e8a7c7d3f797f5f4598a266c.png)
