通过QT实现自定义的对话框

自定义了一个QDialog,并通过信号和槽的机制实现了控件之间的通信,细节见注释



 

//对话框头文件
#ifndef FUCKQT_H
#define FUCKQT_H

#include<QDialog>

class QCheckBox;
class QLabel;
class QLineEdit;
class QPushButton;

class phuckDlg :public QDialog{

	//如果需要在对话框类中自定义信号和槽,则需要在类内添加Q_OBJECT
	Q_OBJECT
public:
	//构造函数,析构函数
	phuckDlg(QWidget *parent = NULL);
	~phuckDlg();

	//在signal和slots中定义这个对话框所需要的信号。
signals:
	//signals修饰的函数不需要本类实现。他描述了本类对象可以发送那些求助信号
	void findNext(const QString& str1, Qt::CaseSensitivity cs);
	void findPrevious(const QString& str1, Qt::CaseSensitivity cs);

//slots必须用private修饰
private slots:
	void findClicked();
	void enableFindButton(const QString& str);

//申明这个对话框需要哪些组件
private:
	QLabel *label1;
	QLineEdit *edit1;
	QCheckBox *box1, *box2;
	QPushButton *findButton, *closeButton;
};

#endif // FUCKQT_H
//定义了控件和控件之间的关联,以及控件的位置
#include<QtGui>
#include<QLabel>
#include<QLineEdit>
#include<QCheckBox>
#include<QPushButton>
#include<QHBoxLayout>
#include "fuckqt.h"
phuckDlg::phuckDlg(QWidget *parent)
	: QDialog(parent)
{

	//初始化控件对象
	//tr是把当前字符串翻译成为其他语言的标记
	//&后面的字母是用快捷键来激活控件的标记,例如可以用Alt+w激活Find &what这个控件
	label1 = new QLabel(tr("Find &what:"));
	edit1 = new QLineEdit;
	//设置伙伴控件
	label1->setBuddy(edit1);
	box1 = new QCheckBox(tr("Mach &case"));
	box2 = new QCheckBox(tr("Search &background"));
	findButton = new QPushButton(tr("&find"));
	findButton->setDefault(true);
	findButton->setEnabled(false);

	closeButton = new QPushButton(tr("close"));

	//连接信号和槽
	connect(edit1, SIGNAL(textChanged(const QString&)), this, SLOT(enableFindButton(const QString&)));
	connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked()));
	connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));

	//设置控件位置
	QHBoxLayout *topLeftLayout = new QHBoxLayout;
	topLeftLayout->addWidget(label1);
	topLeftLayout->addWidget(edit1);

	QVBoxLayout *leftLayout = new QVBoxLayout;
	leftLayout->addLayout(topLeftLayout);
	leftLayout->addWidget(box1);
	leftLayout->addWidget(box2);

	QVBoxLayout *rightLayout = new QVBoxLayout;
	rightLayout->addWidget(findButton);
	rightLayout->addWidget(closeButton);
	rightLayout->addStretch();

	QHBoxLayout *mainLayout = new QHBoxLayout;
	mainLayout->addLayout(leftLayout);
	mainLayout->addLayout(rightLayout);

	this->setLayout(mainLayout);

	setWindowTitle(tr("phuck"));

	setFixedHeight(sizeHint().height());
}

void phuckDlg::findClicked(){
	QString text1 = edit1->text();
	Qt::CaseSensitivity cs;
	if (box1->isChecked()){
		cs = Qt::CaseSensitive;
	}
	else{
		cs = Qt::CaseInsensitive;
	}

	//判断发送什么信号
	if (box2->isChecked()){
		emit findPrevious(text1, cs);
	}
	else{
		emit findNext(text1, cs);
	}
}


void phuckDlg::enableFindButton(const QString& str){
    findButton->setEnabled(!str.isEmpty());
}

phuckDlg::~phuckDlg()
{

}
//测试这个类
#include "fuckqt.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	phuckDlg *dialog = new phuckDlg();
	dialog->show();
	return a.exec();
}

猜你喜欢

转载自bbezxcy.iteye.com/blog/2303829