免责声明,我今天才刚刚下载了Qt,没有使用经验。所以如果这有点愚蠢,我很抱歉。总得从某个地方开始:)。
我将使用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()));
^发布于 2016-09-16 19:35:15
不!!
仅供参考:信号和插槽可以被任何qt对象使用,这就是QPolygon!
bool QObject::connect(const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection)我们使用的connect实际上是QObject::connect(const QObject * sender_object,const char* signal,const QObject receiver_object,const char ),所以无论是发送还是接收,它都能在每个QObject上工作。
在你的例子中,正如hayt在评论中提到的,QPolygon没有hovered()信号,这就是它不能工作的原因。你应该到qt官方网站上的QPolygon文档去阅读它。
据我所知,QPolygon没有信号,因此不能在信号和插槽中使用:)
发布于 2016-09-16 23:29:49
不总是这样。在Qt5中,你当然可以将一个信号连接到“任何东西”上,例如,一个非qobject上的方法,或者连接到一个functor。但是你不能将无信号连接到任何东西上,而且QGraphicsPolygonItem上没有hovered信号,因为它不是QObject,所以它不能有任何信号。
相反,您需要创建一个将QGraphicsSceneEvent转换为信号的filter对象。例如:
// 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"https://stackoverflow.com/questions/39528030
复制相似问题