0

Qtでプログラムを作成したいのですが、2つのボタンのいずれかを押すと、変更したボタンに応じてQLabelのテキストが変わります。スクリプトの実行時にランタイムエラーが発生します。このプログラム用に「カスタム」ウィンドウクラスを作成しました。

これはヘッダーファイルです:

#ifndef MW_H
#define MW_H
#include <QString>
#include <QPushButton>
#include <QLabel>
#include <QGridLayout>
#include <QDialog>

class MW: public QDialog
{
 Q_OBJECT
    private:
    QPushButton* one;
    QPushButton* two;
    QLabel* three;
    QGridLayout* mainL;
public:
    MW();
    private slots:
    void click_1();
    void click_2();

};

#endif // MW_H

これは、ヘッダーの.cppです。

#include "MW.h"

MW :: MW()
{

    //create needed variables
    QGridLayout* mainL = new QGridLayout;
    QPushButton* one = new QPushButton("Set1");
    QPushButton* two = new QPushButton("Set2");
    QLabel* three = new QLabel("This text will be changed");

    //connect signals and slots

    connect(one, SIGNAL(clicked()), this, SLOT(click_1()));
    connect(two, SIGNAL(clicked()), this, SLOT(click_2()));

    // create layout
    mainL->addWidget(one, 1, 0);
    mainL->addWidget(two, 1, 1);
    mainL->addWidget(three, 0, 1);
    setLayout(mainL);
}


void MW :: click_1()
{
    three->setText("One Clicked me!");
}

void MW :: click_2()
{
    three->setText("Two Clicked me!");
}

そして最後に、これが主な機能です。

#include <QApplication>
#include "MW.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MW w;
    w.setAttribute(Qt::WA_QuitOnClose);
    w.show();

    return a.exec();
}

これは私が行っている3番目かそこらの小さな学習プログラムであり、私は同じ問題で立ち往生しています。少し面倒になり始めています。どんな助けでもありがたいです。

4

2 に答える 2

3

エラーはコンストラクター内にあります。

QLabel* three = new QLabel("This text will be changed");

この行は、新しいQLabelをクラス変数ではなくローカル変数に格納します。そのため、クラス変数threeは空のままです。(他の3つの変数と同様ですが、コンストラクターの外部でそれらにアクセスしないため、ここでは問題になりません)

長いことを短くするには、次のようにコードを修正します。

MW :: MW()
{

    //create needed variables
    mainL = new QGridLayout;
    one = new QPushButton("Set1");
    two = new QPushButton("Set2");
    three = new QLabel("This text will be changed"); //This line, actually.

    //connect signals and slots

    connect(one, SIGNAL(clicked()), this, SLOT(click_1()));
    connect(two, SIGNAL(clicked()), this, SLOT(click_2()));

    // create layout
    mainL->addWidget(one, 1, 0);
    mainL->addWidget(two, 1, 1);
    mainL->addWidget(three, 0, 1);
    setLayout(mainL);
}

このように、クラス内の変数が入力され、コードは期待どおりに機能するはずです。

于 2013-03-02T12:52:58.780 に答える
1

あなたの問題はこれです:

QGridLayout* mainL = new QGridLayout;
QPushButton* one = new QPushButton("Set1");
QPushButton* two = new QPushButton("Set2");
QLabel* three = new QLabel("This text will be changed");

クラスメンバーと同じ名前の4つの新しい変数を作成しています。これらの新しい変数は、クラスメンバーを非表示にします。したがって、上記のコードではMW::three、特に初期化することはありません。スロットが呼び出されると、初期化されthree->setText(...)ていないポインタが逆参照され、データが壊れます。

そのコードを次のように置き換えます。

mainL = new QGridLayout;
one = new QPushButton("Set1");
two = new QPushButton("Set2");
three = new QLabel("This text will be changed");
于 2013-03-02T12:53:06.130 に答える