Tôi muốn tạo cửa sổ toàn màn hình với nền trong suốt, nhưng tiện ích con hoàn toàn có thể nhìn thấy (loại hiệu ứng lớp phủ).PyQt5: Tạo cửa sổ bán trong suốt với con không trong suốt
Dưới đây là những gì tôi có cho đến nay:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
app = QApplication(sys.argv)
# Create the main window
window = QMainWindow()
window.setWindowOpacity(0.3)
window.setAttribute(Qt.WA_NoSystemBackground, True)
window.setWindowFlags(Qt.FramelessWindowHint)
# Create the button
pushButton = QPushButton(window)
pushButton.setGeometry(QRect(240, 190, 90, 31))
pushButton.setText("Finished")
pushButton.clicked.connect(app.quit)
# Center the button
qr = pushButton.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
pushButton.move(qr.topLeft())
# Run the application
window.showFullScreen()
sys.exit(app.exec_())
này tạo ra một hiệu ứng bán trong suốt, nhưng ngay cả những nút là bán trong suốt.
Tôi cũng đã cố gắng để thay thế các
window.setWindowOpacity(0.3)
với cuộc gọi này
window.setAttribute(Qt.WA_TranslucentBackground, True)
nhưng không có kết quả, trong trường hợp này nền là hoàn toàn minh bạch (trong khi nút là đúng hoàn toàn có thể nhìn thấy).
Giải pháp: (thực hiện nhờ vào đề nghị của Aaron):
Bí quyết là trong việc thực hiện một paintEvent tùy chỉnh cho cửa sổ chính.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class CustomWindow(QMainWindow):
def paintEvent(self, event=None):
painter = QPainter(self)
painter.setOpacity(0.7)
painter.setBrush(Qt.white)
painter.setPen(QPen(Qt.white))
painter.drawRect(self.rect())
app = QApplication(sys.argv)
# Create the main window
window = CustomWindow()
window.setWindowFlags(Qt.FramelessWindowHint)
window.setAttribute(Qt.WA_NoSystemBackground, True)
window.setAttribute(Qt.WA_TranslucentBackground, True)
# Create the button
pushButton = QPushButton(window)
pushButton.setGeometry(QRect(240, 190, 90, 31))
pushButton.setText("Finished")
pushButton.clicked.connect(app.quit)
# Center the button
qr = pushButton.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
pushButton.move(qr.topLeft())
# Run the application
window.showFullScreen()
sys.exit(app.exec_())
gì xảy ra được rằng nút vẫn là bán trong suốt, và nền được thiết lập một màu hệ thống được xác định (thay vì màu đen, nó bây giờ là màu trắng). Tôi không chắc chắn setWindowOpacity hoạt động trên các widget không cửa sổ. – Enuy
Đã chỉnh sửa câu trả lời của tôi. Tôi đã làm nó như thế này đôi khi và nó luôn luôn làm việc khi bạn cần nó. – Aaron
Được rồi, tôi sẽ cố gắng chuyển đổi mã giả QT này thành PyQT và xem cách nó hoạt động ra sao. – Enuy