以前在dialog或者widget下代码添加控件能显示,但是今天发现在mainwindow下居然不能显示,后来查了资料才知道,需要先定义一个widget,具体代码如下:
QWidget *center = new QWidget(this);
setCentralWidget(center);
penColorComboBox = new QComboBox;
createColorComboBox(penColorComboBox);
penColorLabel = new QLabel(tr("pen color"));
penColorLabel->setBuddy(penColorComboBox);
penWidthspinbox = new QSpinBox;
penWidthspinbox->setRange(0,20);
penWidthspinbox->setSpecialValueText(tr("0 (cosmetic pen)"));
penWidthLabel = new QLabel(tr("pen &width"));
penWidthLabel->setBuddy(penWidthspinbox);
createStyleComboBox();
penStyleLabel = new QLabel(tr("&pen style"));
penStyleLabel->setBuddy(penStyleComboBox);
brushColorComboBox = new QComboBox();
createColorComboBox(brushColorComboBox);
brushColorLabel = new QLabel(tr("Brush Color"));
brushColorLabel->setBuddy(brushColorComboBox);
brushStyleComboBox = new QComboBox;
brushStyleComboBox->addItem(tr("None"),Qt::NoBrush);
brushStyleLabel = new QLabel(tr("&Brush Style"));
brushStyleLabel->setBuddy(brushStyleComboBox);
preLabel = new QLabel(this);
connect(penColorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(penchange()));
connect(penWidthspinbox,SIGNAL(valueChanged(int)),this,SLOT(brushchange()));
connect(penStyleComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(penchange()));
connect(brushColorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(brushchange()));
connect(brushStyleComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(brushchange()));
//connect(this,SIGNAL(penchange(QPen&)),;
QGridLayout *mainlayout=new QGridLayout(center);
mainlayout->addWidget(penColorLabel,0,0,Qt::AlignRight);
mainlayout->addWidget(penColorComboBox,0,1);
mainlayout->addWidget(penWidthLabel,1,0,Qt::AlignRight);
mainlayout->addWidget(penWidthspinbox,1,1);
mainlayout->addWidget(penStyleLabel,2,0,Qt::AlignRight);
mainlayout->addWidget(penStyleComboBox,2,1);
mainlayout->addWidget(brushColorLabel,3,0,Qt::AlignRight);
mainlayout->addWidget(brushColorComboBox,3,1);
mainlayout->addWidget(brushStyleLabel,4,0,Qt::AlignRight);
mainlayout->addWidget(brushStyleComboBox,4,1);
mainlayout->addWidget(preLabel,5,0,6,2);
setLayout(mainlayout);