参考QT的示例里的Examples/Qt-5.5/widgets/tutorials/gettingStarted/gsQt/part3,其中没有用UI设计文件,直接使用Layout。其具体实现为:
class Notepad : public QWidget
{
Q_OBJECT
public:
Notepad();
private slots:
void quit();
private:
QTextEdit *textEdit;
QPushButton *quitButton;
};
Notepad::Notepad()
{
textEdit = new QTextEdit;
quitButton = new QPushButton(tr("Quit"));
connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));
QVBoxLayout *layout = new QVBoxLayout;//创建一个纵向布局
layout->addWidget(textEdit);//将QTextEdit控件天骄到布局当中
layout->addWidget(quitButton);//将QPushButton控件天骄到布局当中
setLayout(layout);//窗口使用此布局
setWindowTitle(tr("Notepad"));
}
我的界面设计当中使用了以下的控件及布局:
//layout com data
QTextEdit *com_data_edit;//串口接收到的数据在此显示
QVBoxLayout *layout_com_data;//com_data_edit放到此布局当中
//layout file data
QPushButton *open_file_btn;
QPushButton *send_file_btn;
QPushButton *save_data_btn;
QPushButton *clear_data_btn;
QLineEdit *file_name_edit;//选择的文件路径在此显示
QCheckBox *hex_check_box;//接收到的数据HEX显示
QHBoxLayout *layout_file_data;//以上6个空间放在横向布局中
//layout port
QLabel *port_label;
QLabel *baudrate_label;
QLabel *data_bits_label;
QLabel *stop_bit_label;
QLabel *parity_bit_label;
QLabel *flow_control_label;
QComboBox *port_combo_box;//串口列表
QComboBox *baudrate_combo_box;//波特率列表
QComboBox *data_bits_combo_box;//数据位列表
QComboBox *stop_bit_combo_box;//停止位列表
QComboBox *parity_bit_combo_box;//校验位列表
QComboBox *flow_control_combo_box;//流控制列表
QPushButton *open_com_btn;//打开串口按键
QHBoxLayout *layout_port;//以上13个控件放在此横向布局中
//layout para checkbox
QCheckBox *dtr_check_box;//dtr使能
QCheckBox *rts_check_box;//rts使能
QCheckBox *regularly_send_check_box;//定时发送
QCheckBox *hex_send_check_box;//HEX发送
QCheckBox *extend_func_check_box;//扩展功能
QLineEdit *time_edit;//定时发送时间
QLabel *regularily_send_label;
QPushButton *send_data_btn;//发送按键
QPushButton *help_btn;
QHBoxLayout *layout_para_check_box;//以上9个控件放在此横向布局中
//layout send
QTextEdit *send_data_edit;//发送数据的编辑框
QVBoxLayout *layout_send_data_text;//放在此布局中
QVBoxLayout *layout_total;//以上的布局放在此纵向布局中,并将此布局设置为窗口布局
在界面规划中,如果QLineEdit控件不想随着窗口大小的变化而变化(比如鼠标拖动),可以通过调用 setMinimumWidth及setMaximumWidth来控制。在我的布局中:
layout_total->addLayout(layout_com_data);
layout_total->addLayout(layout_file_data);
layout_total->addLayout(layout_port);
layout_total->addLayout(layout_para_check_box);
layout_total->addLayout(layout_send_data_text);
layout_total->setAlignment(layout_file_data, Qt::AlignLeft);
layout_total->setAlignment(layout_port, Qt::AlignLeft);
layout_total->setAlignment(layout_para_check_box, Qt::AlignLeft);
layout_total->setAlignment(layout_send_data_text, Qt::AlignLeft);
setLayout(layout_total);
通过调用setAlignment,可以设置布局里的子布局的对齐方式,在窗口大小改变时(比如鼠标拖动),改变的效果不同,在此我设置的是左对齐。