简体   繁体   English

子类化 QLabel 并在 QWidget 类中使用它

[英]Subclassing QLabel and use it in QWidget class

When i try to put QLabel in QWidget class its not work properly (no hover event or click event only the label pixmap is show) only the last instance work properly, when not use set parent, it create in new window for each label but its work correctly当我尝试将 QLabel 放在 QWidget 类中时,它无法正常工作(没有悬停事件或单击事件,仅显示标签像素图)只有最后一个实例正常工作,当不使用 set parent 时,它会在新窗口中为每个标签创建,但它的正常工作

this gif show the problem:这个 gif 显示了问题:

https://media.giphy.com/media/3o7TKKmZSISGXN4Opq/giphy.gif https://media.giphy.com/media/3o7TKKmZSISGXN4Opq/giphy.gif

this is QLabel subclass header:这是 QLabel 子类标题:

#include <QObject>
#include <QLabel>
class myLabel : public QLabel
{
    Q_OBJECT
public:
    myLabel();

protected:
    void mousePressEvent(QMouseEvent *);
    void enterEvent(QEvent *);
    void leaveEvent(QEvent *);


signals :
    void labelClicked();
    void enterSignal();
    void leaveEventSignal();

private:

};

this class to make a labelButton:这个类来制作一个labelButton:

#include <QObject>
#include <QWidget> 
#include "mylabel.h"
class labelButton : public QWidget
{
    Q_OBJECT
public:
    labelButton();

    //some functions

private slots:
    //slots

private:
   //private member
};

and this the class that i want to use the labelButtons in:这是我想在其中使用 labelButtons 的类:

#include <QWidget> 
#include "labelbutton.h"

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;

    labelButton *b_1, *b_2, *b_3;

};

here is widget.cpp:这是widget.cpp:

   Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    b_1 = new labelButton;
    b_1->setParent(this);
    b_1->moveButton(70, 100);
    //some functions to initialize the labelButton
    b_1->show();

    //-----------------------

    b_2 = new labelButton;
    b_2->setParent(this);
    b_2->moveButton(70, 200);
    //some functions to initialize the labelButton
    b_2->show();

    //-----------------------

    b_3 = new labelButton;
    b_3->setParent(this);
    b_3->moveButton(70, 300);
    //some functions to initialize the labelButton
    b_3->show();
}

here its work, the problem was in passing the parent i made a function that take a widget and set buttons parent from the function value这是它的工作,问题是在传递父级时我做了一个函数,该函数接受一个小部件并从函数值中设置按钮父级

b_1 = new labelButton;
//b_1->setParent(this); 
b_1->setParentFunc(this);
b_1->moveButton(70, 100);
//some functions to initialize the labelButton
// b_1->show();

in labelButton:在标签按钮中:

void labelButton::setParentFunc(QWidget *p)
{
    myParent = p;
}

mLabel_1->setParent(myParent); // myParent instead of this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM