How do I connect slot to user defined variable in Qt?

两盒软妹~` 提交于 2019-12-24 14:45:22

问题


Sorry if I'm missing something obvious, but I can't seem to find an answer to my question. Any help would be appreciated.

I am trying to use a QSlider to manipulate data in a class I created.

In the main window constructor I have the following:

connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(setValue(int)));

With a slot defined in the same class:

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private:
    AFrame *frame;
    Ui::MainWindow *ui;

public slots:
    void setValue(int val)
    {
        frame->setMphValue(val);
    }

};

My frame class is a promoted widget to allow for drawing over the image I have set and is defined as follows:

class AFrame : public QLabel
{
    Q_OBJECT

public:
    AFrame( QWidget *parent );
    void setMphValue(int val) { m_mph = val; }

protected:
    void paintEvent( QPaintEvent *event );

private:
    int m_mph;

};

The problem is that when I try assigning the m_mph value in the paintEvent function of the AFrame class, the integer value is lost.

Is there something obvious that I'm missing? Is there a better way to approach this problem?

And my paintEvent code:

void AFrame::paintEvent(QPaintEvent *event)
{

    QLabel::paintEvent(event);
    QPainter painter(this);

    QPen pen("#FF0099");
    pen.setWidth(8);


    painter.setPen(pen);

    //rpm
    painter.drawLine(250,275,165,165);

    //oil
    painter.drawLine(450,100,400,75);

    //fuel
    painter.drawLine(650,95,600,65);

    //mph

    QRect rec(0,0,125,3);

    int velocity = m_mph;
    int rpmStartVal = -225;
    float mph = velocity * 1.68;

    painter.translate(870,275);
    painter.rotate(rpmStartVal + mph);

    painter.drawRect(rec);


 }

回答1:


The integer value is not being lost. The widget has no magical insight into the fact that it should repaint when the mph value is updated. Your setMphValue should look like below. That's all there's to it.

void setMphValue(int val) {
   m_mph = val;
   update();
}



回答2:


To add to Kuba's reply:

You should also check whether val is the same value as previous, in order to avoid avoid repainting when it's not actually necessary - and side-effect infinite loops should anything called by update() later touch setMphValue().

In full:

void setMphValue(int val) {
   if (val == m_mph) return;
   m_mph = val;
   update();
}


来源:https://stackoverflow.com/questions/10849149/how-do-i-connect-slot-to-user-defined-variable-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!