我是qt的新手。实际上我有我的项目的形象。我需要使用click事件在图像上显示图像和文本。我尝试使用QLabel
来显示图像和文本,但它不支持点击事件。这是我尝试过的:
mylabel->setText("Wh");
mylabel->setStyleSheet(QString("QLabel {background-image: url(\"sample.bmp\");color : blue;}"));
mylabel->setGeometry(10,10,78,78);
mylabel->setFont(QFont("Arial", 12));
mylabel->setAlignment(Qt::AlignCenter);
我尝试过鼠标事件,它也可以正常工作,但我不知道如何将事件位置与标签位置(xpos,ypos)进行比较。此外,如果我在运行时更改标签(setGeometry)的位置,则比较标签位置(xpos,ypos)会更加困难。我使用了像我这样的mouseRelease事件,
void SampleProject::mouseReleaseEvent(QMouseEvent* event)
{
int Xpos=event->x();
int Ypos=event->y();
QString s = QString::number(Xpos);
QString t = QString::number(Ypos);
QMessageBox::question(this, s, t, QMessageBox::Yes|QMessageBox::No);
emit clicked(event->pos());
}
答案 0 :(得分:0)
我不确定我是否明白你的要求是正确的,但如果我这样做了,你应该将QLabel
作为子类并使用它mouseReleaseEvent
而不是全局一。如果您愿意,还可以为鼠标点击制作自己的信号:
class MyLabel : public QLabel
{
Q_OBJECT
public:
void mouseReleaseEvent(QMouseEvent *ev) override
{
setText("I have been clicked!");//you can change the text here directly on click
QLabel::mouseReleaseEvent(ev);
emit clicked();//or you can emit a signal, and use it elsewhere
}
signals:
void clicked();
};
如果您发出clicked
信号,您可以轻松获得插槽中贴有标签的标签:
class LabelClickHandler : public QObject
{
Q_OBJECT
public slots:
void onLabelClicked()
{
MyLabel * label = dynamic_cast<MyLabel*>(sender());
//do some stuff with the label
}
};