Qt中一些实用的技巧
当QLabel中的文字过长,在最后面显示省略号QString newStrMsg = "1234567890abcdefghijklmnopqrstuvwxyz";QFontMetrics fontWidth(ui->noteValueLabel->font());//得到每个字符的宽度QString elideNote = fontWidth.elidedText(newStrMsg
当QLabel中的文字过长,在最后面显示省略号
QString newStrMsg = "1234567890abcdefghijklmnopqrstuvwxyz";
QFontMetrics fontWidth(ui->noteValueLabel->font()); //得到每个字符的宽度
QString elideNote = fontWidth.elidedText(newStrMsg, Qt::ElideRight, 150); //最大宽度150像素
ui->noteValueLabel->setText(elideNote);
ui->noteValueLabel->setToolTip(newStrMsg);
寻找文件夹中所有的某格式文件
bool scanData(const QDir& fromDir, const QStringList& filters = { "*.obj" });
bool QtTest::scanData(const QDir& fromDir, const QStringList& filters)
{
QFileInfoList fileInfoList = fromDir.entryInfoList(filters, QDir::AllDirs | QDir::Files);
foreach(QFileInfo fileInfo, fileInfoList)
{
if (fileInfo.fileName() == "." || fileInfo.fileName() == "..")
continue;
if (fileInfo.isDir())
{
if (!scanData(fileInfo.filePath(), filters))
return false;
}
else
{
filePathList.append(fileInfo.absoluteFilePath());
}
}
return true;
}
QPushButton设置菜单后取消右下角下拉三角形
m_pushButton->setStyleSheet("QPushButton::menu-indicator{image:none;}");
在qss中使用变量
QString color = "#00FF00";
QString styleSheet = "QLabel { background-color: %1;}";
ui.label->setStyleSheet(styleSheet.arg(color));
相对路径和绝对路径的转换
// 相对路径转绝对路径
QString relativePath = "./Test/test.txt"
QDir dir;
QString path = dir.absoluteFilePath(relativePath);
// 绝对路径转相对路径
QString absolutePath = "/home/wangjun/Test/test.txt"
QDir dir;
QString path = dir.relativeFilePath(abslutePath);
获取文件路径中的各类名字
// 绝对路径
QFileInfo fi("c:/temp/foo"); => fi.absoluteFilePath() => "C:/temp/foo"
// 文件名
QFileInfo fi("/tmp/archive.tar.gz");
QString base = fi.baseName(); // base = "archive"
// 文件名带半后缀
QFileInfo fi("/tmp/archive.tar.gz");
QString base = fi.completeBaseName(); // base = "archive.tar"
// 后缀名
QFileInfo fi("/tmp/archive.tar.gz");
QString ext = fi.suffix(); // ext = "gz"
// 完整后缀名
QFileInfo fi("/tmp/archive.tar.gz");
QString ext = fi.completeSuffix(); // ext = "tar.gz"
// 文件名带后缀
QFileInfo fi("/tmp/archive.tar.gz");
QString name = fi.fileName(); // name = "archive.tar.gz"、
QPushButton/QToolButton设置选中状态
思路:为Button设置Icon为具体图标,设置border-image为选中状态的边框图
![]()
// QPushButton类似
auto btn_1 = new QToolButton(this);
btn_1->setFixedSize(QSize(30, 30));
btn_1->setIcon(QIcon(":/img.png"));
btn_1->setStyleSheet("QToolButton{ border-image: url(:/test.png); }");
btn_1->setCheckable(true);
btn_1->setChecked(true);
this->layout()->addWidget(btn_1);
connect(btn_1, &QToolButton::clicked, this, [=]()
{
if (btn_1->isChecked())
{
btn_1->setStyleSheet("QToolButton{ border: none; }");
}
else
btn_1->setStyleSheet("QToolButton{ border-image: url(:/test.png); }");
});
QPushButton/QToolButton设置互斥
![]()
auto btn1 = new QPushButton();
auto btn2 = new QPushButton();
QButtonGroup* buttonGround = new QButtonGroup();
buttonGrounp->addButton(btn1);
buttonGrounp->addButton(btn2);
buttonGrounp->setExclusive(true);
QButtonGroup不选中任何按钮
QButtonGroup中默认必须有一个被选中,且无法取消其选中状态Qt官方描述如下:In an exclusive group, the user cannot uncheck the currently checked button by clicking on it; instead, another button in the group must be clicked to set the new checked button for that group。参照stackoverflow上的问答,可以自定义QToollButton解决此问题,链接如下:https://stackoverflow.com/questions/15177771/alternative-to-qbuttongroup-that-allows-no-selection
class CustomButton : public QToolButton
{
Q_OBJECT
public:
CustomButton (QWidget* apo_parent = 0, const char* as_name = 0);
virtual ~CustomButton ();
protected:
virtual void mousePressEvent(QMouseEvent* a_Event);
};
void CustomButton ::mousePressEvent(QMouseEvent* a_Event)
{
if(group() && isToggleButton())
{
CustomButton* selectedButton(dynamic_cast<CustomButton*>(group()->selected()));
if(selectedButton)
{
if(selectedButton->name() == name())
{
group()->setExclusive(false);
toggle();
group()->setExclusive(true);
return;
}
}
}
QToolButton::mousePressEvent(a_Event);
}
将控件放入布局中的指定位置
auto lbl_1 = new QLabel("Test", this);
dynamic_cast<QVBoxLayout*>(this->layout())->insertWidget(1, lbl_1);
调用系统默认程序打开某文件
QDesktopServices::openUrl(QUrl("C://Users//wangjun//Desktop//qt5_cadaques.pdf"));
设置QSlider不可移动
slider.setEnabled(false);
QTimer和QThread
// 在构造函数中
thread = new QThread(this);
thread->start();
QTimer *timer = new QTimer(0);
timer->setInterval(100);
connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()), Qt::DirectConnection);
timer->start();
timer->moveToThread(thread);
// 在析构函数中
thread->quit();
if(!t->wait(3000)) // Wait until it actually has terminated (max. 3 sec)
{
thread->terminate(); // Thread didn't exit in time, probably deadlocked, terminate it!
thread->wait(); // We have to wait again here!
}
获取当前程序中的模态窗口
QApplication::activeModalWidget
在构造函数中退出程序
1.exit(-1)
2.QTimer::singleShot(0, qApp, SLOT(quit()))
判断鼠标是否在某一控件上
if(btn->geometry().contains(this->mapFromGlobal(QCursor::pos())))
枚举与字符串的相互转换
class QtTest : public QWidget
{
Q_OBJECT
public:
QtTest(QWidget *parent = 0);
enum Color { RED, GREEN, BLUE };
Q_ENUM(Color)
private:
Ui::QtTest10Class ui;
};
QtTest10::QtTest10(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QMetaEnum metaColor = QMetaEnum::fromType<Color>();
qDebug() << metaColor.valueToKey(BLUE);
qDebug() << metaColor.keyToValue("BLUE", &isOk) << isOk;
qDebug() << metaColor.keyToValue("BLUE", &isOk) << isOk;
}
QListWidget设置item可编辑
item->setFlags(item->flags() | Qt::ItemIsEditable);
QWidget像QDialog一样阻塞窗口
connect(ui->pushButton, &QPushButton::clicked, this, [=]()
{
QWidget widget;
widget.setAttribute(Qt::WA_ShowModal, true);
widget.show();
QEventLoop loop;
loop.exec();
}
打印当前Qt版本
qDebug() << QT_VERSION_STR;
更多推荐


所有评论(0)