C++ qt QWidget 点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4024923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:18:52  来源:igfitidea点击:

qt QWidget click

c++qtsignals-slots

提问by 0xAX

I have my own class based in QWidget. I put this widget in QMainWindow and I need catch mouse click on this widget.

我有自己的基于 QWidget 的类。我把这个小部件放在 QMainWindow 中,我需要在这个小部件上点击鼠标。

I tried:

我试过:

connect(my_widget, SIGNAL(clicked()), this, SLOT(exit(0)));

But nothing is happening. How can I do it?

但什么也没有发生。我该怎么做?

回答by Live

QWidget does not have a clicked() signal, and QMainWindow does not have an exit() slot. It is impossible to connect to an unexisting signal and unexisting slot. The return value of the connect must be true if the connect is successful. Check this value when you make connections to be sure that your code will work correctly.

QWidget 没有 clicked() 信号,并且 QMainWindow 没有 exit() 槽。不可能连接到不存在的信号和不存在的插槽。如果连接成功,则连接的返回值必须为真。建立连接时检查此值以确保您的代码能够正常工作。

To exit your application, you must call qApp->quit()

要退出您的应用程序,您必须调用 qApp->quit()

Also, as it has been mentioned by others, you will have to install an eventFilter or reimplement the

此外,正如其他人所提到的,您必须安装 eventFilter 或重新实现

void QWidget::mousePressEvent ( QMouseEvent * event )   [virtual protected]

or

或者

void QWidget::mouseReleaseEvent ( QMouseEvent * event )   [virtual protected]

methods.

方法。

There are plenty of examples in the official doc of Qt, thisfor example reimplements the mousePressEvent(QMouseEvent *event)method.

有很多的例子在Qt的官方文档,这个例如重新实现的mousePressEvent(QMouseEvent *event)方法。

For the eventFilter option, see thissmall example.

对于 eventFilter 选项,请参阅小示例。

Hope this helps.

希望这可以帮助。

回答by Eli Bendersky

A QWidgethas no clickedsignal. To make this work, use events. All widgets support events, so there's some manual work to do, but not much:

AQWidget没有clicked信号。要完成这项工作,请使用事件。所有小部件都支持事件,因此需要一些手动工作,但不多:

  1. Override the eventfunction for your widget (which you derive from QWidget
  2. Respond to events of type QEvent:: MouseButtonPress
  1. 覆盖event小部件的功能(您从QWidget
  2. 响应类型事件 QEvent:: MouseButtonPress

Alternatively, add a eventFiltermethod.

或者,添加一个eventFilter方法。

Google the classes and methods I mentioned for code samples and to get to a complete solution depending on your exact needs.

谷歌我提到的代码示例的类和方法,并根据您的确切需求获得完整的解决方案。