main()函数
在main()函数中调用 QMessageBox
之前一定要创建 QApplication
对象, 使用 QWidget
之前要创建 QApplication
对象. 不然会程序崩溃.
下面是笔者原先的代码:
之前是因为数据库等一切正常, 所以没有触发到连接数据库失败的 QMessageBox
消息. 后来有一次连接的时候数据库名忘了换才发现这个问题.
int main(int argc, char *argv[])
{//连接数据库if (!connectToDatabase()) {//连接失败则提示QMessageBox::warning(nullptr, "连接数据库提示", "连接数据库失败, 无法进行登陆");return -1;}else {qDebug() << "连接数据库成功\n";}QApplication a(argc, argv);Login w;w.show();return a.exec();
}
修正后的代码:
int main(int argc, char *argv[])
{//必须在使用QWidget对象之前创建Application对象//之前没有失败是因为数据库都成功连接上了,这次没成功连接上,结果程序直接调用QMessageBox然后崩溃了QApplication a(argc, argv); //连接数据库if (!connectToDatabase()) {//连接失败则提示QMessageBox::warning(nullptr, "连接数据库提示", "连接数据库失败, 无法进行登陆");return -1;}else {qDebug() << "连接数据库成功\n";}Login w;w.show();return a.exec();
}
其实也可以用 qDebug()
来代替 QMessageBox::warning()
, 这样更简单些.
连接MySQL时
数据库名错误, 之前插入数据的时候总是报以下错误, 搞了半天是自己连错了数据库, 里面有一张同名的表, 设定的列不一样.
column count doesn't match value at row 1
输出错误信息: lastError()
qDebug() << "SQL Error:" << query.lastError().text();
插入数据到数据库, 对应的列不全时, 应当一一指出:
以下为数据库的表, 因为 registerDate
列使用的是时间戳自动记录, 所以原先在SQL语句中忽略了这一项导致错误, 查询了好久才找到问题所在.
CREATE TABLE EmployeeInfo (NAME VARCHAR(20),sex VARCHAR(4),PASSWORD VARCHAR(60),tele VARCHAR(11),address VARCHAR(60),remark VARCHAR(100),registerDate TIMESTAMP
);
一一指定就不会出现列不正确的错误了:
QString sql = QString("insert into EmployeeInfo ""(userName, sex, password, tele, address, remark) ""values ('%1', '%2', '%3', '%4', '%5', '%6');").arg(userName).arg(sex).arg(password).arg(tele).arg(address).arg(remark);
使用时间戳自动记录当前时间:
在数据库中加一列 TIMESTAMP
类型的列, 在添加记录的时候它就会自动把当前时间添加进去, 但注意使用insert into
语句插入时一定要指定列和数据.
insert into <TableName> (Columns ...) values (Values...);
控件
QComboBox
控件是一个一个单选框.
可以使用 QComboBox
类中的成员函数 currentText()
去获取其控件上选择的字符串.
ui->sexComboBox->currentText();
currentText()
功能描述:
This property holds the current text
If the combo box is editable, the current text is the value displayed by the line edit. Otherwise, it is the value of the current item or an empty string if the combo box is empty or no current item is set.
RadioButton
是一个单选列表.
可以使用其成员函数 isChecked()
去检测其选中状态, 被选中的返回 true
, 未选中则返回 false
isChecked()
功能描述:
This property holds whether the button is checked.
Only checkable buttons can be checked. By default, the button is unchecked.
QLineEdit
是一行输入框
其中 placeholderText
这个属性可以显示一些提示信息,比如:请输入密码之类的
添加资源
添加图片
- 右击项目,选择
添加新文件
- 选择
Qt
->Recourse file
, 并自行命名
- 右击资源文件,选择open in edit
- 再选择添加文件