我将使用[thing1]和[thing2],1是GraphicsWidget中的qpolygon,2是Widget。
[thing1] = scene->addPolygon([pathname],Pen,Brush)
ui->[thing2]->hide();
connect([thing1],SIGNAL(hovered()),ui->[thing2],SLOT(show()));
我正试图隐藏/显示鼠标悬停事件,但我收到错误
D:\Documents\Test\GUI\mainwindow.cpp:61: error: no matching function for call to 'MainWindow::connect(QGraphicsPolygonItem*&, const char*, MainWindow*, QTextEdit*&, const char*)'
connect([thing1],SIGNAL(hovered()),this,ui->[thing2],SLOT(show()));
^
答案 0 :(得分:0)
NO !!
仅供参考:任何qt对象都可以使用信号和插槽,QPolygon就是这样!
bool QObject::connect(const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection)
我们使用的连接实际上是QObject :: connect(const QObject * sender_object,const char * signal,const QObject receiver_object,const char ),因此无论是发送还是接收,它都适用于每个QObject。
在你的情况下,正如hayt的评论中所提到的,QPolygon没有hovered()信号,这就是为什么它不起作用。 你应该去qt官方网站上的QPolygon文档并阅读它。
据我所知,QPolygon没有信号,所以它不能用于信号和插槽:)
答案 1 :(得分:0)
并非总是如此。在Qt 5中,您当然可以将信号连接到"任何",例如非qobject或仿函数的方法。但是,您无法将非信号连接到任何内容,并且hovered
上没有QGraphicsPolygonItem
信号,因为它不是QObject
,所以它无法发出任何信号。
相反,您需要创建一个将QGraphicsSceneEvent
转换为信号的过滤器对象。 E.g:
// https://github.com/KubaO/stackoverflown/tree/master/questions/polygon-sigslot-39528030
#include <QtWidgets>
class HoverFilter : public QGraphicsObject {
Q_OBJECT
bool sceneEventFilter(QGraphicsItem * watched, QEvent *event) override {
if (event->type() == QEvent::GraphicsSceneHoverEnter)
emit hoverEnter(watched);
else if (event->type() == QEvent::GraphicsSceneHoverLeave)
emit hoverLeave(watched);
return false;
}
QRectF boundingRect() const override { return QRectF{}; }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) override {}
public:
Q_SIGNAL void hoverEnter(QGraphicsItem *);
Q_SIGNAL void hoverLeave(QGraphicsItem *);
};
QPolygonF equilateralTriangle(qreal size) {
return QPolygonF{{{0.,0.}, {size/2., -size*sqrt(3.)/2.}, {size,0.}, {0.,0.}}};
}
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget ui;
QVBoxLayout layout{&ui};
QGraphicsView view;
QLabel label{"Hovering"};
layout.addWidget(&view);
layout.addWidget(&label);
label.hide();
ui.show();
QGraphicsScene scene;
view.setScene(&scene);
HoverFilter filter;
QGraphicsPolygonItem triangle{equilateralTriangle(100.)};
scene.addItem(&filter);
scene.addItem(&triangle);
triangle.setAcceptHoverEvents(true);
triangle.installSceneEventFilter(&filter);
QObject::connect(&filter, &HoverFilter::hoverEnter, [&](QGraphicsItem * item) {
if (item == &triangle) label.show();
});
QObject::connect(&filter, &HoverFilter::hoverLeave, [&](QGraphicsItem * item) {
if (item == &triangle) label.hide();
});
return app.exec();
}
#include "main.moc"